思想:
DFS。
由于每个字符可出现的次数不限,所以首先对数据集这里进行了排序,每一次往下一层前进的时候,起点还是i,直到不能前进,回退,i++。
class Solution {
public:
//Combination Sum
void dfs(vector<int> &candidates, int target, int start, vector<int> &value, vector<vector<int>> &res) {
if(target == 0) {
res.push_back(value);
return;
}
for(int i = start; i < candidates.size(); i++) {
if(target < candidates[i]) return;
value.push_back(candidates[i]);
dfs(candidates, target-candidates[i], i, value, res);
value.pop_back();
}
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> res;
vector<int> value;
dfs(candidates,target,0,value,res);
return res;
}
};
java code:
public class Solution {
/**
* @param candidates: A list of integers
* @param target:An integer
* @return: A list of lists of integers
*/
public List<List<Integer>> combinationSum(int[] candidates, int target) {
// write your code here
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> ans = new ArrayList<Integer>();
Arrays.sort(candidates);
dfs(res, ans, candidates, target, 0);
return res;
}
public void dfs(List<List<Integer>> res, List<Integer> ans, int[] candidates, int target, int start) {
if(target == 0) {
res.add(new ArrayList<Integer>(ans));
return;
}
int prev = -1;
for(int i = start; i < candidates.length; ++i) {
if(target < candidates[i]) return;
if(prev != -1 && prev == candidates[i]) continue;
ans.add(candidates[i]);
dfs(res, ans, candidates, target - candidates[i], i);
ans.remove(ans.size() - 1);
prev = candidates[i];
}
}
}