[LeetCode] 494. Target Sum(目標和)
阿新 • • 發佈:2020-11-23
-
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]
+
和 -
,對於每一個整數,你需要從這兩個符號中選擇一個作為這個數的符號。
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)
}
}