标签:
Title:
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:
For example, given candidate set 2,3,6,7
and target 7
,
A solution set is: [7]
[2, 2, 3]
思路:基本是DFS的思想。将数组排序之后,每次对当前的这个元素与target比较,看最多能塞进去几个当前的这个元素。
如果数组有相同元素,可以采用注释掉的语句进行去重,或者在递归函数中去重。不去重也不会影响结果。
for (int i = (target / candidates[idx]); i >= 0; i--) { record.push_back(candidates[idx]); }
用来计算最多压入几个当前元素。
for (int i = (target / candidates[idx]); i >= 0; i--) { record.pop_back(); searchAns(ans, record, candidates, target - i * candidates[idx], idx + 1,candidates[idx]); //record.pop_back(); }
弹出栈,再进入递归函数。注意,有可能这个元素就不要压入,所以是i >=0
class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(candidates.begin(), candidates.end());
/*vector<int>::iterator pos = unique(candidates.begin(), candidates.end());
candidates.erase(pos, candidates.end());*/
vector<vector<int> > ans;
vector<int> record;
searchAns(ans, record, candidates, target, 0,-1);
return ans;
}
private:
void searchAns(vector<vector<int> > &ans, vector<int> &record, vector<int> &candidates, int target, int idx, int preValue) {
if (target == 0) {
ans.push_back(record);
return;
}
if ( idx == candidates.size() || candidates[idx] > target || preValue == candidates[idx]) {
return;
}
for (int i = (target / candidates[idx]); i >= 0; i--) {
record.push_back(candidates[idx]);
}
for (int i = (target / candidates[idx]); i >= 0; i--) {
record.pop_back();
searchAns(ans, record, candidates, target - i * candidates[idx], idx + 1,candidates[idx]);
//record.pop_back();
}
}
};
标签:
原文地址:http://www.cnblogs.com/yxzfscg/p/4446513.html