Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8 ,
A solution set is:
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]<Solution>
這題是 Combination Sum 的衍生,一樣要求不重複的排列組合的和
差別在於,每個數字只能用一次
可以基於之前的解法,修改一下來避免重複
- 為了要避開重複,先 sort
- 因為每個數字只能用一次,所以每次的 recursive, start = i+1
- 在 DFS 的 for loop 裡面,增加以下片段來避免重複
if(i > start && candidates[i] == candidates[i-1]) {
continue;
}
code 如下
c++, O(2^n)
kotlin, O(2^n)
沒有留言:
張貼留言