rabbbit
2018-08-07 12:29:41 +08:00
搞错了,应该是和 39 题比较像,因为可以重复点菜.
暴力搜索...
```
var combinationSum = function (candidates, target) {
let min = Infinity;
let solution = [];
len = candidates.length;
let callback = function (i, target, arr) {
if (target <= 0 && Math.abs(target) <= min) {
if (Math.abs(target) === min) {
solution.push(arr.slice());
} else {
solution = [arr.slice()];
}
min = Math.abs(target);
} else if (target > 0) {
while (i < len) {
arr.push(candidates[i]);
callback(i, target - candidates[i], arr);
arr.pop();
i++;
}
}
}
callback(0, target, []);
return [min, solution];
};
console.log(combinationSum([1], 2));
// [ 0, [ [ 1, 1 ] ] ]
console.log(combinationSum([1, 2], 3.1));
// [ 0.8999999999999999, [ [ 1, 1, 1, 1 ], [ 1, 1, 2 ], [ 2, 2 ] ] ]
console.log(combinationSum([1, 2, 3], 5));
// [ 0, [ [ 1, 1, 1, 1, 1 ], [ 1, 1, 1, 2 ], [ 1, 1, 3 ], [ 1, 2, 2 ], [ 2, 3 ] ] ]
```