回溯法题目

LeetCode 39 Combination Sum

    给出一个不重复的数组和一个target,数组中元素可以重复使用,输出所有可能的组合

Given a set of candidate numbers (candidates(without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]
代码:
class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(),candidates.end());
        vector<vector<int>> ans;
        vector<int> temp;
        dfsSearch(ans,temp,candidates,target,0);
        return ans;
    }
private:
    void dfsSearch(vector<vector<int>>& ans,vector<int>& temp,vector<int>& candidates,int target,int index){
        if(target==0){
            ans.push_back(temp);
        }
        for(int i=index;i<candidates.size()&&candidates[i]<=target;++i){
            temp.push_back(candidates[i]);
            dfsSearch(ans,temp,candidates,target-candidates[i],i);
            temp.pop_back();
        }
    }
};

LeetCode 39 Combination Sum II

   此题不允许出现重复答案,重复答案的来源在于重复的输入数字。采用set对重复答案进行排除,思路同上一题

代码:

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(),candidates.end());
        vector<vector<int>> ans;
        vector<int> temp;
        dfsSearch(ans,temp,candidates,target,0);
        return ans;
    }
private:
    set<vector<int>> test_set;
    void dfsSearch(vector<vector<int>>& ans,vector<int>& temp,vector<int>& candidates,int target,int index){
        if(target==0&&test_set.find(temp)==test_set.end()){
            ans.push_back(temp);
            test_set.insert(temp);
        }  
        for(int i=index;i<candidates.size()&&candidates[i]<=target;++i){
            temp.push_back(candidates[i]);
            dfsSearch(ans,temp,candidates,target-candidates[i],i+1);
            temp.pop_back();
        }
    }
};

猜你喜欢

转载自blog.csdn.net/qianli2333/article/details/80594602