publicvoidbacktrack(int[] nums, int target, int index, int sum) { if (index == nums.length) { if (sum == target) { count++; } } else { backtrack(nums, target, index + 1, sum + nums[index]); backtrack(nums, target, index + 1, sum - nums[index]); } } }
publicvoidBacktrack(int[] nums, int target, int index, int sum) { if (index == nums.Length) { if (sum == target) { count++; } } else { Backtrack(nums, target, index + 1, sum + nums[index]); Backtrack(nums, target, index + 1, sum - nums[index]); } } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var findTargetSumWays = function(nums, target) { let count = 0; constbacktrack = (nums, target, index, sum) => { if (index === nums.length) { if (sum === target) { count++; } } else { backtrack(nums, target, index + 1, sum + nums[index]); backtrack(nums, target, index + 1, sum - nums[index]); } } backtrack(nums, target, 0, 0); return count; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcfindTargetSumWays(nums []int, target int) (count int) { var backtrack func(int, int) backtrack = func(index, sum int) { if index == len(nums) { if sum == target { count++ } return } backtrack(index+1, sum+nums[index]) backtrack(index+1, sum-nums[index]) } backtrack(0, 0) return }
voidbacktrack(vector<int>& nums, int target, int index, int sum){ if (index == nums.size()) { if (sum == target) { count++; } } else { backtrack(nums, target, index + 1, sum + nums[index]); backtrack(nums, target, index + 1, sum - nums[index]); } } };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int count;
intfindTargetSumWays(int* nums, int numsSize, int target) { count = 0; backtrack(nums, numsSize, target, 0, 0); return count; }
voidbacktrack(int* nums, int numSize, int target, int index, int sum) { if (index == numSize) { if (sum == target) { count++; } } else { backtrack(nums, numSize, target, index + 1, sum + nums[index]); backtrack(nums, numSize, target, index + 1, sum - nums[index]); } }
复杂度分析
时间复杂度:O(2^n),其中 n 是数组 nums 的长度。回溯需要遍历所有不同的表达式,共有 2^n 种不同的表达式,每种表达式计算结果需要 O(1) 的时间,因此总时间复杂度是 O(2^n)。
空间复杂度:O(n),其中 n 是数组 nums 的长度。空间复杂度主要取决于递归调用的栈空间,栈的深度不超过 n。
funcfindTargetSumWays(nums []int, target int)int { sum := 0 for _, v := range nums { sum += v } diff := sum - target if diff < 0 || diff%2 == 1 { return0 } n, neg := len(nums), diff/2 dp := make([][]int, n+1) for i := range dp { dp[i] = make([]int, neg+1) } dp[0][0] = 1 for i, num := range nums { for j := 0; j <= neg; j++ { dp[i+1][j] = dp[i][j] if j >= num { dp[i+1][j] += dp[i][j-num] } } } return dp[n][neg] }
intfindTargetSumWays(int* nums, int numsSize, int target) { int sum = 0; for (int i = 0; i < numsSize; i++) { sum += nums[i]; } int diff = sum - target; if (diff < 0 || diff % 2 != 0) { return0; } int neg = diff / 2; int dp[neg + 1]; memset(dp, 0, sizeof(dp)); dp[0] = 1; for (int i = 0; i < numsSize; i++) { int num = nums[i]; for (int j = neg; j >= num; j--) { dp[j] += dp[j - num]; } } return dp[neg]; }