Leetcode|Combination Sum II[递归回溯]

来源:互联网 发布:移动的网络电视盒子 编辑:程序博客网 时间:2024/04/30 09:18

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

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 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
先排序!
这个题,去重是关键;//[2,2,2,2] 4 怎么快速去重呢?
先抛出个很笨重的去重吧。40ms
解法1:

class Solution {public:    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {        sort(candidates.begin(),candidates.end());        vector<int> temp;        vector<vector<int>> res;        combinationSum(candidates,0,target,temp,res);        return res;    }private:    void combinationSum(vector<int>& candidates,int index,int target,vector<int> temp,vector<vector<int>> &res){        if(index==candidates.size()||candidates[index]>target) return;//终止条件        if(candidates[index]==target){            temp.push_back(candidates[index]);            if(res.size()>0){//skip duplicates too slow!!!                for(int i=0;i<res.size();i++){                    if(equal(temp,res[i])) return;                }            }//不重复就加入!//但是这判断重复的代价太大了吧???            res.push_back(temp);//找到一组满足条件的             return;        }         temp.push_back(candidates[index]);         combinationSum(candidates,index+1,target-candidates[index],temp,res);         temp.pop_back();         combinationSum(candidates,index+1,target,temp,res);    }    bool equal(vector<int> &a,vector<int> &b){        if(a.size()!=b.size()) return false;        for(int i=0;i<a.size();i++){            if(a[i]!=b[i]) return false;        }        return true;    }};

每次都是把整个res中的vector全部比较一遍,时间成本很高。
要想出在刚开始就去掉的方法!
解法2:把后面相同的元素跳过去。20ms

public:    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {        sort(candidates.begin(),candidates.end());        vector<int> temp;        vector<vector<int>> res;        combinationSum(candidates,0,target,temp,res);        return res;    }private:    void combinationSum(vector<int>& candidates,int index,int target,vector<int> temp,vector<vector<int>> &res){      if(index==candidates.size()||candidates[index]>target) return;//终止条件        for(int i=index;i<candidates.size();i++){            if(i>index&&candidates[i]==candidates[i-1])                  continue;            temp.push_back(candidates[i]);            if(candidates[i]==target){               res.push_back(temp);//找到一组满足条件的                return;            }            combinationSum(candidates,i+1,target-candidates[i],temp,res);            temp.pop_back();        }    }
0 0
原创粉丝点击