From abefd5840b64b3f82148bf383499bd854f20e42d Mon Sep 17 00:00:00 2001 From: zhoutianyi Date: Sun, 27 Oct 2024 23:39:32 -0400 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=9B=AE=E6=A0=87=E5=92=8C?= =?UTF-8?q?=20go=20=E5=9B=9E=E6=BA=AF=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0494.目标和.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index 08724609..09e77b12 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -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 {