[LeetCode] 494. Target Sum(目标和)
-
Difficulty: Medium
-
Related Topics: Dynamic Programming, Depth-first Search
Description
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.
给定一个包含非负整数的列表 [a1, a2, ..., an]
,以及一个目标 S。你有两个符号 +
和 -
,对于每一个整数,你需要从这两个符号中选择一个作为这个数的符号。
Find out how many ways to assign symbols to make sum of integers equal to target S.
找出有多少种赋值的方式,使得赋值过后这些数的和等于 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.
Constraints
- The length of the given array is positive and will not exceed 20.
给定的数组保证非空,且长度不超过 20。 - The sum of elements in the given array will not exceed 1000.
给定数组的元素和不超过 1000。 - Your output answer is guaranteed to be fitted in a 32-bit integer.
你的答案保证在 32 位整数的范围内。
Solution
由于此题只出现 + 和 -,没有其它符号,所以简单的深搜即可完成任务。代码如下:
class Solution {
private var result = 0
fun findTargetSumWays(nums: IntArray, S: Int): Int {
backtrack(nums, S, 0, 0)
return result
}
private fun backtrack(nums: IntArray, s: Int, curSum: Int, curIndex: Int) {
if (curIndex == nums.size ) {
if (curSum == s) {
result++
}
return
}
// 当前数的符号取 +
backtrack(nums, s, curSum + nums[curIndex], curIndex + 1)
// 当前数的符号取 -
backtrack(nums, s, curSum - nums[curIndex], curIndex + 1)
}
}