在JavaScript中生成所需的组合
如果只能使用1到9之间的数字,并且该组合应该是一组唯一的数字,则该函数应找到加总为n的m个数字的所有可能组合。
例如-如果输入是-
const m = 3, n = 4;
那么输出应该是-
const output = [ [1, 2, 4] ];
如果输入是-
const m = 3, n = 9;
那么输出应该是-
const output = [ [1, 2, 6], [1, 3, 5], ];
示例
为此的代码将是-
const m = 3, n = 9;
const findSum = (m, n) => {
const search = (from, prefix, m, n) => {
if (m === 0 && n === 0) return res.push(prefix);
if (from > 9) return;
search(from + 1, prefix.concat(from), m − 1, n − from);
search(from + 1, prefix, m, n);
};
const res = [];
search(1, [], m, n);
return res;
};
console.log(findSum(m, n));输出结果
控制台中的输出将是-
[ [ 1, 2, 6 ], [ 1, 3, 5 ], [ 2, 3, 4 ] ]