码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 494. Target Sum

时间:2018-12-03 23:02:27      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:添加   solution   example   lis   The   guarantee   sign   target   vector   

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.

分析

题目的意思等价于把题目中给定的集合中挑选元素分成两个集合,set1,set2,然后用set1的和减去set2的和等于S。
set1-set2=S;
set1-(sum-set1)=S;
set1=(S+sum)/2;
所以题目转化成在集合中挑选元素使其和为(S+sum)/2.

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        int sum=accumulate(nums.begin(),nums.end(),0);
        return sum<S||(S+sum)%2>0?0:Sumset(nums,(S+sum)/2);
    }
    int Sumset(vector<int>& nums,int s){
        int dp[s+1]={0};
        dp[0]=1;
        for(auto num:nums)
            for(int i=s;i>=num;i--)
                dp[i]+=dp[i-num];
        return dp[s];
    }
};

这道题用dfs也可以,尝试为每个数前面添加 + 或 -。

class Solution {
public:
    int res=0;
    void dfs(int cnt,int sum,vector<int>& nums,int S){
        if(cnt==nums.size()){
            if(sum==S)
             res++;  
             return ;
        }      
        dfs(cnt+1,sum+nums[cnt],nums,S);
        dfs(cnt+1,sum-nums[cnt],nums,S);
    }
    int findTargetSumWays(vector<int>& nums, int S) {
        dfs(0,0,nums,S);
        return res;
    };
};

LeetCode 494. Target Sum

标签:添加   solution   example   lis   The   guarantee   sign   target   vector   

原文地址:https://www.cnblogs.com/A-Little-Nut/p/10061285.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!