4.15 39.组合总和
给你一个 无重复元素 的整数数组 candidates
和一个目标整数 target
,找出 candidates
中可以使数字和为目标数 target
的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates
中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target
的不同组合数少于 150
个。
示例 1:
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。
示例 2:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3:
输入: candidates = [2], target = 1
输出: []
我的思路:
找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 并以列表形式返回。
它可以是重复的
不需要startIndex,每次都从数组[0]开始遍历
但是答案错误啦!处理相同的排序应该怎么办,通过index进行去重
2 3 5
235 35 5
sum += candidates[i];if(sum > target ){break;}
如果是这样当sum>tartget的时候直接break了,i+1,又继续 sum += candidates[i];
就会导致sum一直比startget大
我的代码:
function combinationSum(candidates: number[], target: number): number[][] {const path = [];//存储每一次递归树的const res = [];//存储答案function backtracking(sum : number , startIndex:number){if(sum === target){res.push([...path]);return;}for(let i = startIndex ; i < candidates.length ; i++){sum += candidates[i];if(sum > target ){sum -= candidates[i]; // 回溯sumbreak;}path.push(candidates[i]);backtracking(sum , i);//因为可以使用重复的数字,所以是isum -= candidates[i];path.pop();}}backtracking(0 , 0);return res;};
解答错误:使用 break 会导致循环提前终止,而您想要的是在 sum 超过 target 时继续尝试下一个候选数字。因此,应该使用 continue 而不是 break。
最终代码:
function combinationSum(candidates: number[], target: number): number[][] {const path = [];//存储每一次递归树的const res = [];//存储答案function backtracking(sum : number , startIndex:number){if(sum === target){res.push([...path]);return;}for(let i = startIndex ; i < candidates.length ; i++){sum += candidates[i];if(sum > target ){sum -= candidates[i]; // 回溯sumcontinue;}path.push(candidates[i]);backtracking(sum , i);//因为可以使用重复的数字,所以是isum -= candidates[i];path.pop();}}backtracking(0 , 0);return res;};
总结:这一道题目我看到允许重复就直接for循环从i=0,开始的但是我还是忽略了[2,3,3][3,2,3]其实是一样的。在之前我们的startIndex=i+1,这里我们只需要startIndex=i就可以啦!在处理sum>target的时候也要注意,因为我们>之后还要继续循环其他的数字,所以不是break,此外我们还要还原sum