标签:添加 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:
分析
题目的意思等价于把题目中给定的集合中挑选元素分成两个集合,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;
};
};
标签:添加 solution example lis The guarantee sign target vector
原文地址:https://www.cnblogs.com/A-Little-Nut/p/10061285.html