Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:
-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
There are 5 ways to assign symbols to make the sum of nums be target 3.
我可以独立作出leetcode的题了,哈哈哈,值得纪念
class Solution {
int count = 0;
public int findTargetSumWays(int[] nums, int S) {
int length = nums.length;
int sum = 0;
helper(nums, S, sum, 0);
return count;
}
public void helper(int[] nums, int S, int sum, int d){
if(d == nums.length){
if(sum == S)
count++;
sum = S - nums[d - 1];
return;
}
helper(nums, S, sum + nums[d], d + 1);
helper(nums, S, sum - nums[d], d + 1);
}
}