// dp 解法
public class Solution {
public int findTargetSumWays(int[] nums, int S) {
if (nums == null || nums.length == 0) return 0;
int sum = 0, n = nums.length;
for (int num : nums) {
sum += num;
}
if (sum < S) return 0;
sum += S;
if ((sum & 1) == 1) return 0;
sum /= 2;
int[] dp = new int[sum + 1];
dp[0] = 1;
for (int num : nums) {
for (int i = sum; i >= num; i--) {
dp[i] += dp[i - num];
}
}
return dp[sum];
}
}
// dfs 解法
public class Solution {
int rst = 0;
public int findTargetSumWays(int[] nums, int S) {
dfs(0, 0, nums, S);
return rst;
}
private void dfs(int sum, int count, int[] nums, int target) {
if (count == nums.length) {
if (sum == target) {
rst++;
}
return;
}
dfs(sum + nums[count], count + 1, nums, target);
dfs(sum - nums[count], count + 1, nums, target);
}
}