[LeetCode]494. Target Sum

dfs深度优先搜索

Posted by JinFei on December 26, 2019

题目描述

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:

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:

  1. The length of the given array is positive and will not exceed 20.
  2. The sum of elements in the given array will not exceed 1000.
  3. Your output answer is guaranteed to be fitted in a 32-bit integer.

解题思路

  • 深度优先搜索
  • 首先判断一个指针,是否走到了nums的末尾, 注意,由于是末尾,指针应该是等于size
  • 然后判断是否与指定的值相等
  • 当前的值,加上或者减去nums[begin]即可

C++代码

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        int res = 0;
        dfs(nums, res, 0, S, 0);
        return res;
    }
    
    void dfs(vector<int>& nums, int& res, int begin, int target, int cur){
        if(begin == nums.size()){
            if(cur == target){
                res++;
            }
            return;
        }
        dfs(nums, res, begin + 1, target, cur + nums[begin]);
        dfs(nums, res, begin + 1, target, cur - nums[begin]);
    }
};