Target Sum Ways

Problem

Put a + or a - in front of every number of the array, then add them all. Print how many different sign choices give exactly k. For 1 1 1 1 1 and k = 3 there are 5 ways.

Constraints

  • 1 <= n <= 15
  • 1 <= a[i] <= 20
  • |k| <= 300

Examples

Input

5
1 1 1 1 1
3

Output

5

Solutions

Brute forceTime O(2^n)Space O(n)

Every number has two choices, so there are 2^n leaves. Each leaf is checked against k. It is simple but only works for small n.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Count sign choices.
 * Input   : n, the array, then k.
 * Output  : Number of ways.
 * Approach: Try both signs.
 * Time    : O(2^n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
        private static long go(int[] a, int index, int sum, int k) {
            if (index == a.length) {
                return sum == k ? 1 : 0;
            }
            return go(a, index + 1, sum + a[index], k) + go(a, index + 1, sum - a[index], k);
        }

    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[] a, int k) {
        // Step 1: For each number try + and then -. At the end count the choices whose sum is k.
        return go(a, 0, 0, k);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        int k = scanner.nextInt();
        System.out.println(solve(a, k));
    }
}
Hints (2)
  1. How many sign choices are there?
  2. What is the base case?