LeetCode递归解题模板

39

40

78. Subsets https://leetcode.com/problems/subsets/description/

    void subsets(vector<int>& nums, int pos, vector<int>& current, vector<vector<int>>& result){
        if(pos == nums.size()){
            result.push_back(current);
            return;
        }else{
            subsets(nums,pos+1,current,result);
            current.push_back(nums[pos]);
            subsets(nums,pos+1,current,result);
            current.pop_back();
        }
    }
    
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> result;
        vector<int> current;
        subsets(nums, 0, current, result);
        return result;
    }
View Code

使用迭代的方法来做呢?

 

90. Subsets II https://leetcode.com/problems/subsets-ii/description/

void getsubsetsWithDup(vector<int>& nums, int pos, vector<int>& temp, vector<vector<int>>& result) {
    if (pos == nums.size()) {
        result.emplace_back(temp);
        return;
    }
    //nextpos指向下一个不为nums[pos]的位置或为nums.size()
    int nextpos = pos + 1;
    while (nextpos != nums.size() && nums[nextpos] == nums[pos])
        nextpos++;
    getsubsetsWithDup(nums, nextpos, temp, result);
    for (int i = pos; i < nextpos; i++) {
        temp.emplace_back(nums[i]);
        getsubsetsWithDup(nums, nextpos, temp, result);
    }
    temp.erase(temp.end() - (nextpos - pos), temp.end());
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    vector<vector<int>> result;
    vector<int> temp;
    getsubsetsWithDup(nums, 0, temp, result);
    return result;
}
View Code

1、重复的地方在与多个重复元素在一起的时候会出现前一个在、后一个不再和前一个不在、后一个在的这种重复情况,想要去除就在遇到这种情况的时候直接跳过,用不重复的情况代替,不重复的情况是确定个数的重复元素

 

216. Combination Sum III https://leetcode.com/problems/combination-sum-iii/description/

class Solution {
public:
    /*
        pos:遍历到1到9中的哪个位置
        current:当前的数组
    */
    void combinationSum3(vector<vector<int>>& result, int k ,int n, int pos,vector<int>& current){
        if(n == 0 && k== 0){
            result.push_back(current);
            return;
        }else if(n <= 0 || k <= 0 || pos > 9)
            return;
        else{
            for(int i=pos;i<=9;i++){
                if(n-i<0) return;
                current.push_back(i);
                combinationSum3(result,k-1,n-i,i+1,current);
                current.pop_back();
            }
        }
    }
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> result;
        vector<int> current;
        combinationSum3(result, k, n, 1, current);
        return result;
    }
};
View Code

 

posted @ 2019-03-12 14:08  番茄汁汁  阅读(431)  评论(0编辑  收藏  举报