【发布时间】:2021-06-14 11:47:49
【问题描述】:
给定一个从 1 到 n 的序列,我想找到所有 唯一 大小为 m 且总和为 的子序列n。子序列不需要是连续的。例如
if m = 2, n = 5
The possible unique subsequences of size 2 are {1,4} and {2,3}
到目前为止,我已经能够使用递归生成所有子序列,但我的代码不仅仅返回唯一的子序列,结果中有一些重复。
function allCombinations(m, n) {
if (m < 1) {
return [];
}
let helper = function(m, n, arr, result, index){
if (n < 0 || m < 0) {
return 0;
}
if (m === 0 && n === 0) {
result.push(arr.slice());
return 1;
}
for (let i = index; i <= n; i++){
arr.push(i);
helper(m - 1, n - i, arr, result, index + 1);
arr.pop();
}
}
let result = [];
helper(m, n, [], result, 0);
return result;
}
当调用时
let res = allCombinations(2, 5);
结果是
[ [ 1, 4 ], [ 2, 3 ], [ 3, 2 ] ]
如您所见,{3,2} 是 {2,3} 的副本。如何更改我的代码以使其仅返回唯一序列?
【问题讨论】:
标签: javascript algorithm recursion