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.
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.问题分析:
1.暴力求解: 列举出所有的情况,每个数字的可能性有2,一共存在2^(arr.size())种情况,从中pick 出来和为target的样例。
2.二项式(只针对整数取1的情况):sum(+)+sum(-)=N;
sum(+)-sum(-)=target;
sum(+)=(N+target)/2; 也就是说从N个数中要pick出来多少个数使得这几个数的和为sum(+),那么很容易想到即满足二项式Cn sum(+)=就是最终的结果;例如eg1中的sum(+)=(5+3)/2,那么从5个里面选4个出来,最终的final即为5。对于全为1的状态
class Solution {
public:
int multiple(int k){
int sum=1;
for(int i=k;i>0;i--)
sum*=i;
return sum;
}
int findTargetSumWays(vector<int>& nums, int S) {
if((nums.size()+S)%2!=0){
return 0;
}
int target=(nums.size()+S)/2;
return multiple(nums.size())/multiple(target)/multiple(nums.size()-target);
}
};