给定一个从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} 的重复。我该如何更改代码,以便仅返回唯一的序列?