I am solving LeetCode #49 Combination Sum. The idea is to find all the unique combinations that sum to the target.
It's fairly straight forward to find the permutations that add to the sum but I'm stuggling to modify my code to only find unique permutations.
What is the general concept in dynamic programming for getting the unique results with recursion?
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function (candidates, target) {
let distinct = []
let dfs = (candidates, target, list = []) => {
if (target === 0) {
distinct.push(list)
return
}
candidates.forEach((candidate, i) => {
let diff = target - candidate;
if (diff >= 0) {
dfs(candidates, diff, [...list, candidate])
}
})
}
dfs(candidates, target)
return distinct
};
Input:
[2,3,6,7]
7
My Output:
[[2,2,3],[2,3,2],[3,2,2],[7]]
Desired Output:
[[2,2,3],[7]]
How do I avoid duplicates?