Combination sum
Given a set of candidate numbers (C) and a target number (t), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
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 set2,3,6,7
And target7
,
A solution set is:
[7]
[2, 2, 3]
Idea: a typical recursive program traverses the current number and does not retrieve the current number for each traversal.
Class solution {public: void combinationsum (vector <int> & candidates, int index, int currentsum, int target, vector <int> & Path) {If (currentsum = target) {res. push_back (PATH); return;} int length = candidates. size (); If (Index = length | currentsum> Target) return; Path. push_back (candidates [Index]); combinationsum (candidates, index, currentsum + candidates [Index], target, PATH); // Add the current node path again. pop_back (); combinationsum (candidates, index + 1, currentsum, target, PATH ); // skip the current node} vector <int> combinationsum (vector <int> & candidates, int target) {sort (candidates. begin (), candidates. end (); vector <int> path; combinationsum (candidates, target, PATH); Return res;} PRIVATE: vector <int> res ;};
Combination sum II
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,5
And target8
,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Class solution {public: void combinationsum2 (vector <int> & num, int index, int currentsum, int target, vector <int> & Path) {If (currentsum = target) {hash. insert (PATH); // prevent repeated return;} int length = num. size (); If (Index = length | currentsum> Target) return; Path. push_back (Num [Index]); combinationsum2 (Num, index + 1, currentsum + num [Index], target, PATH); // obtain the path of the current node. pop_back (); combinationsum2 (Num, index + 1, currentsum, target, PATH ); // do not retrieve the current node} vector <int> combinationsum2 (vector <int> & num, int target) {sort (Num. begin (), num. end (); vector <int> path; combinationsum2 (Num, 0, 0, target, PATH); vector <int> res (hash. begin (), hash. end (); Return res;} private: Set <vector <int> hash ;};
If you want to calculate the total number and do not need to remove duplicates, you can see here
Combination sum of leetcode