|
| 1 | +package backtracking; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by gouthamvidyapradhan on 09/12/2017. |
| 5 | + * You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. |
| 6 | + * For each integer, you should choose one from + and - as its new symbol. |
| 7 | +
|
| 8 | + Find out how many ways to assign symbols to make sum of integers equal to target S. |
| 9 | +
|
| 10 | + Example 1: |
| 11 | + Input: nums is [1, 1, 1, 1, 1], S is 3. |
| 12 | + Output: 5 |
| 13 | + Explanation: |
| 14 | +
|
| 15 | + -1+1+1+1+1 = 3 |
| 16 | + +1-1+1+1+1 = 3 |
| 17 | + +1+1-1+1+1 = 3 |
| 18 | + +1+1+1-1+1 = 3 |
| 19 | + +1+1+1+1-1 = 3 |
| 20 | +
|
| 21 | + There are 5 ways to assign symbols to make the sum of nums be target 3. |
| 22 | + Note: |
| 23 | + The length of the given array is positive and will not exceed 20. |
| 24 | + The sum of elements in the given array will not exceed 1000. |
| 25 | + Your output answer is guaranteed to be fitted in a 32-bit integer. |
| 26 | + * |
| 27 | + */ |
| 28 | +public class TargetSum { |
| 29 | + |
| 30 | + private static int n; |
| 31 | + /** |
| 32 | + * Main method |
| 33 | + * @param args |
| 34 | + * @throws Exception |
| 35 | + */ |
| 36 | + public static void main(String[] args) throws Exception{ |
| 37 | + int[] A = {1, 1, 1, 1, 1}; |
| 38 | + n = 0; |
| 39 | + new TargetSum().findTargetSumWays(A, 3); |
| 40 | + System.out.println(n); |
| 41 | + } |
| 42 | + |
| 43 | + public int findTargetSumWays(int[] nums, int S) { |
| 44 | + backtrack(nums, S, 0, 0); |
| 45 | + return n; |
| 46 | + } |
| 47 | + |
| 48 | + private void backtrack(int[] nums, int target, int sum, int i){ |
| 49 | + if(i == nums.length){ |
| 50 | + if(sum == target){ |
| 51 | + n++; |
| 52 | + } |
| 53 | + } else{ |
| 54 | + backtrack(nums, target, sum + nums[i], i + 1); |
| 55 | + backtrack(nums, target, sum - nums[i], i + 1); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | +} |
| 60 | + |
0 commit comments