97-Combination Sum

来源:互联网 发布:易建联的雄鹿赛季知乎 编辑:程序博客网 时间:2024/06/05 03:22

-39. Combination Sum My Submissions QuestionEditorial Solution
Total Accepted: 93154 Total Submissions: 298105 Difficulty: Medium
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]

从指定的集合里选出数来组合成指定target(放回式的取,允许重复)

思路:此题思路很重要,可能你会想到划分,dp等
但那不是正确思路

正确思路是dfs,将其当成一片元素严格递增式的森林来搜

class Solution {public:    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        sort(candidates.begin(),candidates.end());        vector<vector<int>> res;        vector<int> tmp;        dfs(candidates,target,0,tmp,res);        return res;    }    void dfs(vector<int> &vec,int gap,int start,vector<int> &tmp,vector<vector<int>> &res)    {           if(gap==0){ //递归出口是找到满足条件的元素               res.push_back(tmp);           }           else{               int n=vec.size();               for(int i=start;i<n;++i){                   if(gap<vec[i])return;//剪枝                   tmp.push_back(vec[i]);//放入中间结果集                   dfs(vec,gap-vec[i],i,tmp,res); //进入子树,但是是标号弱递增式,表示子问题在[当前元素,末尾元素]继续                   tmp.pop_back(); //当前元素不合适,回退               }           }    }};
0 0
原创粉丝点击