494. Target Sum

来源:互联网 发布:汽车单片机控制灯光 编辑:程序博客网 时间:2024/06/03 15:44

You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.

Find out how many ways to assign symbols to make sum of integers equal to target S.

Example 1:

Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5Explanation: -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 = 3There are 5 ways to assign symbols to make the sum of nums be target 3.

Note:

  1. The length of the given array is positive and will not exceed 20.
  2. The sum of elements in the given array will not exceed 1000.

  1. Your output answer is guaranteed to be fitted in a 32-bit integer.
public class Solution {    int solution = 0;    public int findTargetSumWays(int[] nums, int S) {        if(nums == null || nums.length == 0){            return 0;        }        dfs(nums, 0, S, 0);         return solution;    }        public void dfs(int[] nums, int start, int S, int sum){    if(start == nums.length){ //这里要等于,因为要求完最后一个数字    if(sum == S){    solution++;    }    return;    }        dfs(nums, start+1, S, sum+nums[start]);        dfs(nums, start+1, S, sum-nums[start]);    }}

public class Solution {    public int findTargetSumWays(int[] nums, int S) {        int sum = 0;        for (int a : nums) {            sum += a;        }        if (sum < Math.abs(S)) {            return 0;        }        //init for dp        int doubleSum = sum << 1;         int[][] dp = new int[nums.length][doubleSum + 1];        if (nums[0] == 0) {            dp[0][sum] = 2;        } else {            dp[0][sum - nums[0]] = 1;            dp[0][sum + nums[0]] = 1;        }        //dp        for (int i = 1; i < nums.length; i++) {            for (int j = 0; j <= doubleSum; j++) {                if (j - nums[i] >= 0) {                    dp[i][j] += dp[i - 1][j - nums[i]];                }                if (j + nums[i] <= doubleSum) {                    dp[i][j] += dp[i - 1][j + nums[i]];                }            }        }        return dp[nums.length - 1][S + sum];    }}



原创粉丝点击