标签:object backtrack 注意 leetcode === else cat ++ rac
与上一题差不多。但结果不能重复,我们可以做一个去重处理
var combinationSum2 = function (nums, target) {
if (!Object(nums).length) {
return [];
}
nums.sort()
var uniq = {}, result = [], n = nums.length, condidate = []
function backtrack(start, sum) {
if (sum === 0) {
var key = condidate + ""
if (!uniq[key]) {
result.push(condidate.concat());
uniq[key] = 1
}
} else if (sum > 0) {
for (var i = start; i < n; i++) {//注意从0开始,不断尝试
var el = nums[i]
condidate.push(el) //试探
backtrack(i+1, sum - el); //递归自身
condidate.pop(); //不管成功与否,退回上一步
}
}
}
backtrack(0, target);
return result;
};
leetcode 40. Combination Sum II
标签:object backtrack 注意 leetcode === else cat ++ rac
原文地址:https://www.cnblogs.com/rubylouvre/p/12045184.html