Code & Func
2017-10-12

第19天

这道题是在起床到去上课前AC出来的,emmm,大概就10多分钟的样子。。。

虽然后来尝试优化了一下,但是感觉效果都不怎么好。。

题目描述:

Given a set of candidate numbers (C) (without duplicates) 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.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [2, 3, 6, 7] and target 7,A solution set is:

1
[
2
[7],
3
[2, 2, 3]
4
]

其实想法很简单,我既然想求combinationSum(7),通过遍历数组,我们现在有了一个[2],我只需要在求combinatiomSum(7-2)即可,然后组合起来:

1
vector<int> cand;
2
vector<vector<int> > ret;
3
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
4
cand = candidates;
5
sort(cand.begin(),cand.end());
6
vector<int> now;
7
combinationSumIter(now,0,target);
8
return ret;
9
}
10
void combinationSumIter(vector<int> &now,int beg,int target){
11
//cout << "target" << target << endl;
12
for(int i = beg;i < cand.size();++i) {
13
if (target < cand[i])
14
break;
15
else if (target == cand[i]) {
10 collapsed lines
16
vector<int> vec = now;
17
vec.push_back(cand[i]);
18
ret.push_back(vec);
19
} else if (target - cand[i] >= cand[0] ){
20
vector<int> vec = now;
21
vec.push_back(cand[i]);
22
combinationSumIter(vec,i,target-cand[i]);
23
}
24
}
25
}

然后在dicuss中看到的也是类似的想法:

1
class Solution {
2
public:
3
std::vector<std::vector<int> > combinationSum(std::vector<int> &candidates, int target) {
4
std::sort(candidates.begin(), candidates.end());
5
std::vector<std::vector<int> > res;
6
std::vector<int> combination;
7
combinationSum(candidates, target, res, combination, 0);
8
return res;
9
}
10
private:
11
void combinationSum(std::vector<int> &candidates, int target, std::vector<std::vector<int> > &res, std::vector<int> &combination, int begin) {
12
if (!target) {
13
res.push_back(combination);
14
return;
15
}
7 collapsed lines
16
for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i) {
17
combination.push_back(candidates[i]);
18
combinationSum(candidates, target - candidates[i], res, combination, i);
19
combination.pop_back();
20
}
21
}
22
};
上一条动态