本文共 1172 字,大约阅读时间需要 3 分钟。
要解决这个问题,我们可以使用回溯法来找出所有可以组成目标数的组合。以下是详细的解决方案:
combinationSum2 = function (candidates, target) { candidates.sort((a, b) => a - b); const res = []; const dfs = (sum, start, temp) => { if (sum === target) { res.push(temp.slice()); return; } if (sum > target) { return; } for (let i = start; i < candidates.length; i++) { if (i > start && candidates[i] === candidates[i - 1]) { continue; } temp.push(candidates[i]); dfs(sum + candidates[i], i + 1, temp); temp.pop(); } }; dfs(0, 0, []); return res;}; 通过这种方法,我们可以高效地找到所有符合条件的组合,确保每个组合都是唯一的并且满足条件。
转载地址:http://nhqmz.baihongyu.com/