mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 07:06:42 +08:00
@ -706,6 +706,31 @@ class Solution:
|
||||
```
|
||||
|
||||
### Go
|
||||
回溯法思路
|
||||
```go
|
||||
func findTargetSumWays(nums []int, target int) int {
|
||||
var result int
|
||||
var backtracking func(nums []int, target int, index int, currentSum int)
|
||||
|
||||
backtracking = func(nums []int, target int, index int, currentSum int) {
|
||||
if index == len(nums) {
|
||||
if currentSum == target {
|
||||
result++
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 选择加上当前数字
|
||||
backtracking(nums, target, index+1, currentSum+nums[index])
|
||||
|
||||
// 选择减去当前数字
|
||||
backtracking(nums, target, index+1, currentSum-nums[index])
|
||||
}
|
||||
|
||||
backtracking(nums, target, 0, 0)
|
||||
return result
|
||||
}
|
||||
```
|
||||
二维dp
|
||||
```go
|
||||
func findTargetSumWays(nums []int, target int) int {
|
||||
|
Reference in New Issue
Block a user