图(dfs)494. Target Sum[middle]

来源:互联网 发布:鱼骨标本淘宝 编辑:程序博客网 时间:2024/06/06 03:58

题目:

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: 5Explanation: -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 = 3There are 5 ways to assign symbols to make the sum of nums be target 3.

给一串数,一个结果S,在数中间使用+ -运算得到 S


分析:

直觉就是,递归,对一个数,选择+和选择- 分别递归,递归基就是算完了全部的数。


代码:



class Solution {public:    void sum(vector<int>& nums, int& he, int S, int size, int& all) {if (size == nums.size()  && he == S) {    //满足条件的S,计数器加一all++;}if (size < nums.size()) {    //选择 - ,递归he += -nums[size];sum(nums, he, S, size+1, all);he -= -nums[size];        //选择 + ,递归he += nums[size];sum(nums, he, S, size + 1, all);he -= nums[size];}}    int findTargetSumWays(vector<int>& nums, int S) {            int all = 0;int size = 0;int he = 0;sum(nums, he, S, size, all);return all;            }};



递归刚开始接触时并不是很好写的,这道题解法寥寥几句,但是清楚、正确地写出来也不容易……

0 0