All problems

Problem 293

Target Sum

Medium · 20 pts · Array, Dynamic Programming, Backtracking

Problem

You are given N non-negative integers and a target T. Put either a '+' or a '-' sign in front of every number, and add them up. Count the number of sign choices for which the total equals exactly T. Choices are counted by position, so equal numbers at different positions give different choices. If P is the sum of the numbers with a plus sign, then P - (total - P) = T, so P = (total + T) / 2. The problem becomes counting subsets with sum P, a standard subset-count DP (no solutions if total + T is odd or negative).

Input

First line: N and T. Second line: N non-negative integers.

Output

Print the number of ways.

Constraints

1 <= N <= 20; 0 <= A[i] <= 1000; sum of A <= 1000; -1000 <= T <= 1000

Example input

5 3
1 1 1 1 1

Example output

5

Explanation

With five 1's and T = 3, exactly one number must get a minus sign: 1 + 1 + 1 + 1 - 1 = 3. The minus sign can go on any of the 5 positions, so there are 5 ways.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Insertions to Make Palindrome Next: Rod Cutting