标签:bin get pre where code start esc sum ica
题目描述:
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 (a 1, a 2, … , a k) must be in non-descending order.
(ie, a 1 ≤ a 2 ≤ … ≤ a k).
The solution set must not contain duplicate combinations.
For example, given candidate set10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
思路:
和set2的思路一样,从原始的起始点开始一层一层的产生一个个的组合,每一个组合都是由一个前缀+一个元素构成,我们都是在合法前缀基础上产生组合的,所以我们产生的组合不会发生遗漏,同一个前缀加不同的元素构成的组合当然不同,由于前缀不同,由不同的前缀产生的组合之间更不同了,所以这样产生的组合不会重合。
代码:
1 class Solution {
2 public:
3 vector<vector<int> > combinationSum2(vector<int> &num, int target) {
4
5 vector<vector<int>> ret;
6 sort(num.begin(),num.end());
7 vector<int> temp;
8 int curSum = 0;
9 combinationSum2Core(num,0,ret,temp,curSum,target);
10 return ret;
11 }
12
13 void combinationSum2Core(vector<int> &num,int start,vector<vector<int>> &ret,vector<int> &temp,int &curSum,int target)
14 {
15 if(start == num.size())
16 return;
17 for(int i = start;i < num.size();i++)
18 {
19 if(i != start && num[i] == num[i-1])//每一次产生的前缀都是唯一的,满足给定的条件时,以这个
20 continue; //前缀为基础的dfs就可以停止了
21
22 curSum += num[i];
23 if(curSum > target)
24 {
25 curSum-=num[i];
26 return;//剪枝
27 }
28 else if(curSum == target)
29 {
30 temp.push_back(num[i]);
31 ret.push_back(temp);
32 temp.pop_back();
33 curSum-=num[i];
34 return;//剪枝
35 }
36 else
37 {
38 temp.push_back(num[i]);
39 combinationSum2Core(num,i+1,ret,temp,curSum,target);
40 temp.pop_back();
41 curSum-=num[i];
42 }
43 }
44 }
45 };
标签:bin get pre where code start esc sum ica
原文地址:https://www.cnblogs.com/zjuhaohaoxuexi/p/11784757.html