Skip to content

Commit 6018ca4

Browse files
committed
✨494.目标和
1 parent 0958b19 commit 6018ca4

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@
175175
- [386.字典序排数](leetcode/medium/386.go)
176176
- [393.UTF-8 编码验证](leetcode/medium/393.go)
177177
- [429.N 叉树的层序遍历](leetcode/medium/429.go)
178+
- [494.目标和](leetcode/medium/t494/solution.go)
178179
- [513.找树左下角的值](leetcode/medium/513.go)
179180
- [535.TinyURL 的加密与解密](leetcode/medium/535.go)
180181
- [537.复数乘法](leetcode/medium/537.go)

leetcode/medium/t494/solution.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package t494
2+
3+
// 494. 目标和
4+
// https://leetcode.cn/problems/target-sum/
5+
func findTargetSumWays(nums []int, target int) (count int) {
6+
// 定义回溯函数,用于递归地计算所有可能的和
7+
var backtrack func(int, int)
8+
// 回溯函数,递归核心部分,用于计算给定索引位置的元素加减后与目标值的匹配情况。
9+
// 参数:
10+
// index - 当前处理的元素索引。
11+
// sum - 当前路径上的和。
12+
backtrack = func(index, sum int) {
13+
// 如果索引达到数组长度,说明遍历完所有元素
14+
if index == len(nums) {
15+
// 如果当前和等于目标值,增加计数
16+
if sum == target {
17+
count++
18+
}
19+
return
20+
}
21+
// 递归调用,分别尝试加法和减法
22+
backtrack(index+1, sum+nums[index])
23+
backtrack(index+1, sum-nums[index])
24+
}
25+
// 从数组的第一个元素开始回溯,初始和为0
26+
backtrack(0, 0)
27+
// 返回达到目标和的方法总数
28+
return
29+
}

leetcode/medium/t494/solution_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package t494
2+
3+
import "testing"
4+
5+
func TestFindTargetSumWays(t *testing.T) {
6+
tests := []struct {
7+
nums []int
8+
target int
9+
want int
10+
}{
11+
{[]int{1, 1, 1, 1, 1}, 3, 5},
12+
{[]int{1}, 1, 1},
13+
}
14+
for _, tt := range tests {
15+
t.Run("", func(t *testing.T) {
16+
if got := findTargetSumWays(tt.nums, tt.target); got != tt.want {
17+
t.Errorf("findTargetSumWays() = %v, want %v", got, tt.want)
18+
}
19+
})
20+
}
21+
}

0 commit comments

Comments
 (0)