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
vector<vector<int> > res;
vector<int> cache;
sort(candidates.begin(), candidates.end());
calculate(cache, 0, candidates, res, target);
return res;
}
void calculate(vector<int> cache, int curIdx, vector<int>& candidates, vector<vector<int> >& res, int target)
{
if (curIdx >= candidates.size()) return;
int i = 0;
while (target - candidates[curIdx] * i >= 0)
{
for (int j = 0; j < i; ++j)
{
cache.push_back(candidates[curIdx]);
}
if (target - candidates[curIdx] * i == 0)
{
res.push_back(cache);
break;
}
calculate(cache, curIdx + 1, candidates, res, target - candidates[curIdx] * i);
for (int j = 0; j < i; ++j)
{
cache.pop_back();
}
++i;
}
}
};
[Leetcode] Combination Sum
最新推荐文章于 2019-05-07 10:37:18 发布