[LeetCode]Combination Sum

来源:互联网 发布:淘宝卖家怎样优化标题 编辑:程序博客网 时间:2024/04/28 18:42

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] 

LeetCode Source

思路:DFS。或者是采用回溯法。特别注意要先对原数组排序。

class Solution {public:    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {        vector<vector<int> >ret;        vector<int> temp;        sort(candidates.begin(),candidates.end());        for(int i=0;i<candidates.size();++i){            dfs(ret,candidates,i,target,temp);        }        return ret;    }        void dfs(vector<vector<int> >&ret,vector<int> candidates,int i,int target,vector<int> temp){        if(candidates[i]==target){            temp.push_back(candidates[i]);            ret.push_back(temp);            return;        }        if(candidates[i]>target){            return;        }        if(candidates[i]<target){            temp.push_back(candidates[i]);            for(int j=0;j<candidates.size()-i;++j)                dfs(ret,candidates,i+j,target-candidates[i],temp);        }                }};

AC了,但是发现运行时间长达435ms。分析后发现问题出在。

for(int j=0;j<candidates.size()-i;++j)                dfs(ret,candidates,i+j,target-candidates[i],temp);

我们对明显不会有解(j>target-candidates[i])的结果进行了DFS。修改如下,时间减少到30ms。

class Solution {public:    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {        vector<vector<int> >ret;        vector<int> temp;        sort(candidates.begin(),candidates.end());        for(int i=0;i<candidates.size();++i){            if(candidates[i]<=target)            dfs(ret,candidates,i,target,temp);        }        return ret;    }        void dfs(vector<vector<int> >&ret,vector<int> candidates,int i,int target,vector<int> temp){        if(candidates[i]==target){            temp.push_back(candidates[i]);            ret.push_back(temp);            return;        }        if(candidates[i]<target){            temp.push_back(candidates[i]);            for(int j=0;j<candidates.size()-i;++j)                if(candidates[i+j]<=target-candidates[i]){                dfs(ret,candidates,i+j,target-candidates[i],temp);            }        }                }};



0 0
原创粉丝点击