美文网首页
LeetCode Target Sum

LeetCode Target Sum

作者: codingcyx | 来源:发表于2018-03-30 10:54 被阅读0次

    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: 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.
    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.
    3.Your output answer is guaranteed to be fitted in a 32-bit integer.

    class Solution {
    public:
        /*
        int findTargetSumWays(vector<int>& nums, int S) {
            int dp[20][2001] = {0};
            int n = nums.size();
            dp[0][1000 + nums[0]] += 1;
            dp[0][1000 - nums[0]] += 1;
            for(int i = 1; i<n; i++){
                for(int j = -1000; j<=1000; j++){
                    if(dp[i-1][j+1000] > 0){
                        dp[i][j+1000+nums[i]] += dp[i-1][j+1000];
                        dp[i][j+1000-nums[i]] += dp[i-1][j+1000];
                    }
                }
            }
            return S > 1000 || S < -1000 ? 0 : dp[n-1][S+1000];
        }
        */
        int findTargetSumWays(vector<int>& nums, int S) {
            int n = nums.size();
            int dp[2001] = {0};
            dp[1000 + nums[0]] += 1;
            dp[1000 - nums[0]] += 1;
            for(int i = 1; i<n; i++){
                int next[2001] = {0};
                for(int j = -1000; j<=1000; j++){
                    if(dp[j + 1000] > 0){
                        next[j + 1000 + nums[i]] += dp[j + 1000];
                        next[j + 1000 - nums[i]] += dp[j + 1000];
                    }
                }
                memcpy(dp, next, 2001*sizeof(int));
            }
            return S > 1000 || S < -1000 ? 0 : dp[S + 1000];
        }
    };
    

    注:动态规划降低数组维度。

    相关文章

      网友评论

          本文标题:LeetCode Target Sum

          本文链接:https://www.haomeiwen.com/subject/qzwbcftx.html