您的位置:首页 > 其它

[leetcode] 39. Combination Sum 解题报告

2015-12-21 08:41 274 查看
题目链接:https://leetcode.com/problems/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 set
2,3,6,7
and target
7
,

A solution set is:

[7]


[2, 2, 3]


思路:深搜。为保证结果有序,需要将vector首先排序,然后搜索的时候只能搜索本身或者比他大的数。思路比较清晰。写的时候还是忘记首先排序,以为他给的数据就是有序的,好坑!

代码如下:

class Solution {
public:
void DFS(vector<int>& candidates, int target, vector<int> vec, int sum, int index)
{
if(sum == target) return result.push_back(vec);
if(index >= candidates.size() || sum > target) return;
DFS(candidates, target, vec, sum, index+1);
vec.push_back(candidates[index]);
DFS(candidates, target, vec, sum+candidates[index], index);
}

vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
if(candidates.size() ==0) return result;
sort(candidates.begin(), candidates.end());
DFS(candidates, target, vector<int>(), 0, 0);
return result;
}
private:
vector<vector<int>> result;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: