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.

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.
这一题可以用分治算法来解决。

第一个符号可以为:+ 和 -

第二个符号亦同,可以为+和-。那么和第一个符号可以组成++、+-、-+、--

如此进行下去,可构成一棵递归树。

我们设一个函数用来执行递归。令和初始化为sum=0,每递归一次,记录递归的次数i。每一层递归,要么sum += nums[i],要么sum -= nums[i]

直到i = nums.size(),查看是否和target相等。

代码如下:

class Solution {
public:
int count = 0;
int target;
void DP(vector<int>& nums, int sum, int i){
if (i < nums.size()){
   DP(nums, sum+nums[i], i+1);
   DP(nums, sum-nums[i], i+1);
}
else{
   if (sum == target) count++;
}
}

    int findTargetSumWays(vector<int>& nums, int S) {
    target = S;
        DP(nums, 0, 0);
        return count;
    }


};





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值