zoukankan      html  css  js  c++  java
  • Leetcode——Target Sum

    Question

    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:
    The length of the given array is positive and will not exceed 20.
    The sum of elements in the given array will not exceed 1000.
    Your output answer is guaranteed to be fitted in a 32-bit integer.

    Solution

    这道题相当于找一个子集求和减去剩下的集合求和等于目标值。P表示positive, N表示Negitive
    // sum(P) - sum(N) = S
    // sum(P) + sum(N) + sum(P) - sum(N) = S + sum(All)
    // 2sum(P) = sum(All) + S
    // sum(P) = (sum(All) + S) / 2

    解题思想:动态规划。dp[j] = dp[j] + dp[j - n]

    Code

    class Solution {
    public:
        int findTargetSumWays(vector<int>& nums, int S) {
            // sum(P) - sum(N) = S
            // sum(P) + sum(N) + sum(P) - sum(N) = S + sum(All)
            // 2sum(P) = sum(All) + S
            // sum(P) = (sum(All) + S) / 2
            int sum = 0;
            for (int n : nums)
                sum += n;
            if ((sum + S) & 1 == 1 || sum < S)
                return 0;
            sum = (sum + S) / 2;
            return subsetsum(nums, sum);
        }
        int subsetsum(vector<int>& nums, int sum) {
            int dp[sum + 1] = {0};
            dp[0] = 1;
            for (int n : nums) {
                for (int j = sum; j >= n; j--)
                    dp[j] += dp[j - n];
            }
            return dp[sum];
        }
    };
    
  • 相关阅读:
    [转载]Linux 线程实现机制分析
    Linux命令学习总结:cp命令
    ORA-01012: not logged on
    TNS-12540: TNS:internal limit restriction exceeded
    ORACLE临时表空间总结
    ORACLE回收站机制介绍
    SQL Server 2008 R2 Service Pack 3 已经发布
    python中的单下划线和双下划线意义和作用
    redis基本命令的演示:
    redis百度百科和维基百科知识总结:
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/9369882.html
Copyright © 2011-2022 走看看