Combination sum II Total accepted: 13710 total submissions: 55908my submissions
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.
- Elements in a combination (A1, A2 ,... , Ak) must be in Non-descending order. (ie, A1 ≤ A2 ≤... ≤ AK ).
- The solution set must not contain duplicate combinations.
For example, given candidate set10,1,2,7,6,1,5And target8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Given a group of numbers C and a value T, find all the combinations whose sum is equal to T in C. The same number in C can only be obtained once, And the Combinations found cannot be repeated.
Train of Thought: DFS
The J-th node of the I-layer has n-I-j Branch selection
Recursive depth: recursive returns if the sum is greater than or equal to T.
Complexity: time O (N !), Space O (N)
Vector <vector <int> res; vector <int> _ num; void DFS (INT start, int target, vector <int> & Path) {If (target = 0) {res. push_back (PATH); return;} int previous =-1; // Add this to record the previous value of the same layer branch. If the current value is the same as the previous value, skip to avoid repeating for (INT I = start; I <_ num. size (); ++ I) {If (previous = _ num [I]) continue; If (target <_ num [I]) return; // pruning previous = _ num [I]; Path. push_back (_ num [I]); DFS (I + 1, target-_ num [I], PATH); Path. pop_back () ;}}vector <vector <int> combinationsum2 (vector <int> & num, int target) {_ num = num; sort (_ num. begin (), _ num. end (); vector <int> path; DFS (0, target, PATH); Return res ;}
Leetcode DFS combination sumii