• LN : leetcode 494 Target Sum


    lc 494 Target Sum


    494 Target Sum

    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.

    DP Accepted

    数组的数字要么取正要么取负,sum(P)代表所有取正的数的和,sum(N)代表所有取负的数的和。

                    sum(P) - sum(N) = target
    sum(P) + sum(N) + sum(P) - sum(N) = target + sum(P) + sum(N)
                    2 * sum(P) = target + sum(nums)
    

    可以看出:如果target + sum(nums)为奇数,那必定可行方法数为0。之后利用 416 Partition Equal Subset Sum中的方法,即可求得数组中求和得到(target + sum(nums))/2的方法数。

    class Solution {
    public:
        int findTargetSumWays(vector<int>& nums, int S) {
            int sum = accumulate(nums.begin(), nums.end(), 0);
            if (sum < S) return 0;
            else return (S+sum) & 1 ? 0 : subsum(nums, (S+sum)>>1);
        }
        
        int subsum(vector<int>& nums, int S) {
            vector<int> dp(S+1, 0);
            dp[0] = 1;
            for (int n : nums)
                for (int i = S; i >= n; i--)
                    dp[i] += dp[i-n];
            return dp[S];
        }
    };
    
  • 相关阅读:
    Js判断是否改动
    导入用户数据到Discuz! X3.2 并实现同步登陆
    win2003(sp2 x86)+iis6+php-5.3.5-Win32 配置
    bblittle.com
    Macbook Hbase(1.2.6) 伪分布式安装,Hadoop(2.8.2) ,使用自带zookeeper
    LeetCode 696. Count Binary Substrings
    LeetCode 637. Average of Levels in Binary Tree
    LeetCode 226. Invert Binary Tree
    LeetCode 669. Trim a Binary Search Tree
    LeetCode 575. Distribute Candies
  • 原文地址:https://www.cnblogs.com/renleimlj/p/8025194.html
Copyright © 2020-2023  润新知