LeetCode刷题笔记 46. 全排列 78. 子集 【回溯算法模板】

LeetCode刷题笔记 46. 全排列

  • 46. 全排列
  • 78. 子集
    • 流程打印

46. 全排列

回溯算法详解

def backtrack(...):
    for 选择 in 选择列表:
    	排除非法选择
        做选择
        backtrack(...)
        撤销选择
class Solution {
public:
    vector<vector<int>> res;
    void backtrack(vector<int>& nums,vector<int> track){
        if(track.size()==nums.size()){ / 全排列需用到全部元素
            res.push_back(track); 
            return;
        }
        for(int i=0;i<nums.size();i++){
            if(find(track.begin(),track.end(),nums[i])!=track.end()) continue; 
            track.push_back(nums[i]);
            backtrack(nums,track);
            track.pop_back();
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
        vector<int> track;
        backtrack(nums,track);
        return res;
    }
};

find():返回值是目标元素的下标,找不到时返回值为迭代器结尾

78. 子集

https://leetcode-cn.com/problems/subsets/solution/hui-su-suan-fa-by-powcai-5/

class Solution {
public:
    vector<vector<int>> res;
    void backtrack(vector<int>& nums,vector<int> track,int i){        
        res.push_back(track); / 子集需要保存每一种情况
        for(int j=i;j<nums.size();j++){
            track.push_back(nums[j]);
            backtrack(nums,track,j+1);
            track.pop_back();
        }
    }
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<int> track;
        backtrack(nums,track,0);
        return res;
    }
};

流程打印

class Solution {
public:
    vector<vector<int>> res;
    void backtrack(vector<int>& nums,vector<int> track,int i){
        for (auto iter = track.cbegin(); iter != track.cend(); iter++) 
            cout << (*iter) ;
        cout<< endl;        
        res.push_back(track);
        for(int j=i;j<nums.size();j++){
            track.push_back(nums[j]);
            backtrack(nums,track,j+1);
            track.pop_back();
            cout<<"j= "<<j<<endl;
        }
    }
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<int> track;
        backtrack(nums,track,0);
        return res;
    }
};
1
12
123
j= 2
j= 1
13
j= 2
j= 0
2
23
j= 2
j= 1
3
j= 2

你可能感兴趣的:(Leetcode)