mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 15:09:40 +08:00
添加目标和 go 回溯版本
This commit is contained in:
@ -706,6 +706,31 @@ class Solution:
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Go
|
### 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
|
二维dp
|
||||||
```go
|
```go
|
||||||
func findTargetSumWays(nums []int, target int) int {
|
func findTargetSumWays(nums []int, target int) int {
|
||||||
|
Reference in New Issue
Block a user