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.
classSolution{ // DP top-down int[][] memo; publicintfindTargetSumWays(int[] nums, int S){ int sum = 0; for (int num : nums) { sum += num; } memo = newint[nums.length][2 * sum + 1];
for (int i = 0; i < memo.length; i++) { Arrays.fill(memo[i], Integer.MIN_VALUE); }
return dfs(nums, 0, sum, S, 0); }
privateintdfs(int[] nums, int sum, int total, int S, int index){ if (index == nums.length) { if (sum == S) { return1; } else { return0; } } else { if (memo[index][sum + total] != Integer.MIN_VALUE) { return memo[index][sum + total]; }
int add = dfs(nums, sum + nums[index], total, S, index + 1); int substract = dfs(nums, sum - nums[index], total, S, index + 1); memo[index][sum + total] = add + substract;
classSolution{ // DP bottom-up push int[][] dp; publicintfindTargetSumWays(int[] nums, int S){ int sum = 0; for (int num : nums) { sum += num; } int offset = sum;
classSolution{ // DP bottom-up pull int[][] dp; publicintfindTargetSumWays(int[] nums, int S){ int sum = 0; for (int num : nums) { sum += num; } int offset = sum;
classSolution{ publicintfindTargetSumWays(int[] nums, int S){ int sum = 0; for (int num : nums) { sum += num; } if (sum < S) { return0; } if ((S + sum) % 2 == 1) { return0; } int target = (S + sum) / 2;
classSolution{ publicintfindTargetSumWays(int[] nums, int S){ int sum = 0; for (int num : nums) { sum += num; } if (sum < S) { return0; } if ((S + sum) % 2 == 1) { return0; } int target = (S + sum) / 2;
int[] dp = newint[sum + 1]; dp[0] = 1;
for (int num : nums) { // 注意这里初始化的方式!!!不要新建数组,然后指向dp int[] copy = Arrays.copyOfRange(dp, 0, dp.length); for (int j = 0; j <= target; j++) { if (j - num >= 0) { dp[j] += copy[j - num]; } } int y = 0; }