[Leetcode] Combination Sum

来源:互联网 发布:安装快牙软件 编辑:程序博客网 时间:2024/04/29 18:36

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

class Solution {public:    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<vector<int> > result;        vector<int> com;        sort(candidates.begin(),candidates.end());                dfs(result,com,candidates,0,target);        return result;          }        void dfs (vector<vector<int> > &result, vector<int> &com, vector<int> &candidate, int index, int target)    {               for(int i=index;i<candidate.size();i++)        {            if(candidate[index] == target)            {                 com.push_back(candidate[i]);                result.push_back(com);                com.pop_back();                return;            }            else if(candidate[index] > target)            {                return;            }            else            {                com.push_back(candidate[i]);                dfs(result,com,candidate,i,target-candidate[i]);                com.pop_back();            }            index++;        }    }};

 

原创粉丝点击