Leetcode_combination-sum

来源:互联网 发布:西安儿童编程培训机构 编辑:程序博客网 时间:2024/06/14 05:07

地址: http://oj.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 (a1a2, … , 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] 

思路:dfs,控制搜索条件(当vector为空或者要插入的值大于vector中最后一个值时才进行搜索)使结果是升序的(从而消除duplicates combinations)。100ms

参考代码:

class Solution {public:    void dfs(vector<vector<int>>&ans, vector<int>tmpvec, vector<int> &candidates, int target)    {        if(target==0)        {            ans.push_back(tmpvec);            return;        }        for(int i = 0; i<candidates.size(); ++i)        {            if(candidates[i]>target)                break;            if(tmpvec.empty() || candidates[i]>=tmpvec.back())            {                tmpvec.push_back(candidates[i]);                dfs(ans, tmpvec, candidates, target-candidates[i]);                tmpvec.pop_back();            }        }    }    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {        vector<vector<int>>ans;        if(candidates.empty())            return ans;        sort(candidates.begin(), candidates.end());        vector<int>tmpvec;        dfs(ans, tmpvec, candidates, target);        return ans;    }};


0 0
原创粉丝点击