dfs学习之生成目标数方法

LeetCode题目 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.

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.

分析

这道题可以用简单地dfs递归遍历求出所有情况的,然后判断每种情况的结果是否是题目给出的值。思路是,对于第k个树,有两种处理方法,一种是将之前的和与他相加,得到add的结果,另外一种是将之前的和与他相减,得到另外sub的结果。继续递归下去,等到k等于数组的末端时判断这个和是否等于要求值,是的话就count++。
这种做法成本是2^n次方,在此道题的规定范围内还是可以ac的,然后代码也比较优雅。但是还有一种更优化的方法,是动态规划。但现在还没学到,看得不是很懂就先不copy别人的代码。等到下次弄懂再发表新的博客。

代码

class Solution {
public:
    void findTarget(vector<int>& nums, int& count, int pos, int sum, int mySum) {
        int _size = nums.size();
        if (pos == _size) {
            if (mySum == sum) count++;
            return;
        }
        int add = mySum + nums[pos];
        findTarget(nums, count, pos+1, sum, add);
        int sub = mySum - nums[pos];
        findTarget(nums, count, pos+1, sum, sub);
    }


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

附录

题目的LeetCode地址

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值