Given a sequence from 1 to n, I want to find all the unique subsequences of size m that sum up to n. The subsequences don't need to be contiguous. For example
if m = 2, n = 5
The possible unique subsequences of size 2 are {1,4} and {2,3}
So far I've been able to generate all the subsequences using recursion but my code is not returning only the unique subsequences, there are some duplicates in the result.
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;
}
and when calling with
let res = allCombinations(2, 5);
the result is
[ [ 1, 4 ], [ 2, 3 ], [ 3, 2 ] ]
and as you can see {3,2} is a duplicate of {2,3}. How can I change my code so it returns only the unique sequences?