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.

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); 
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值