一、题目描述
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.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] ]思路:用DFS(深度搜索)的方法,原理都懂,看了别人的代码才会写代码(心酸....)。DFS的标准写法大概是这样,记住这个格式吧。
c++代码(64ms,14.68%)
class Solution { public: vector<vector<int> > res; vector<int> ans; vector<vector<int>> combinationSum(vector<int>& candidates, int target) { if(candidates.empty()) return res; dfs(0,0,target,candidates); return res; } void dfs(int start, int sum, int target, vector<int> candidates){ if(sum == target){ res.push_back(ans); return; }else if(sum>target) return; else{ for(int i=start; i<candidates.size(); i++){ ans.push_back(candidates[i]); dfs(i, sum+candidates[i], target, candidates); ans.pop_back(); //pop_back() 删除最后一个元素 } } } };
