494. Target Sum

Target Sum

题目描述:

You are given an integer array nums and an integer target.

You want to build an expression out of nums by adding one of the symbols ‘+’ and ‘-‘ before each integer in nums and then concatenate all the integers.

For example, if nums = [2, 1], you can add a ‘+’ before 2 and a ‘-‘ before 1 and concatenate them to build the expression “+2-1”.
Return the number of different expressions that you can build, which evaluates to target.

Example 1:

Input: nums = [1,1,1,1,1], target = 3
Output: 5
Explanation: There are 5 ways to assign symbols to make the sum of nums be target 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
+1 + 1 + 1 + 1 - 1 = 3
Example 2:

Input: nums = [1], target = 1
Output: 1

Constraints:

1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000

思路:

我用dfs做,做起来简单,但是效率低,用动态规划做会比较好

代码:

func findTargetSumWays(nums []int, target int) int {
    var dfs func(sum, index int) 
    count := 0
    n := len(nums)
    dfs = func(sum, index int){
        if sum == target && index == n{
            count++
            return 
        }
        if index >= n {
            return 
        }
        dfs(sum+nums[index],index+1)
        dfs(sum+-1*nums[index],index+1)
    }
    dfs(0, 0)
    return count
}

代码效率:

执行用时:644 ms, 在所有 Go 提交中击败了23.74%的用户
内存消耗:2 MB, 在所有 Go 提交中击败了98.67%的用户