回溯算法

Leetcode46. 全排列
回溯算法_第1张图片

class Solution {
public:
    vector<vector<int>> ans;
    void func(vector<int> &nums,vector<int> &vec,vector<bool>& choice){
        if(vec.size() == choice.size()){
            ans.push_back(vec);
        }
        for(int i = 0; i < choice.size(); i++){
            if(choice[i] == false){
                vec.push_back(nums[i]);
                choice[i] = true;
                func(nums,vec,choice);
                choice[i] = false;
                vec.pop_back();
            }
        }
        return ;
    }
    vector<vector<int>> permute(vector<int>& nums) {
        vector<bool> choice(nums.size(),false);
        vector<int> vec;
        if(nums.size() == 0){
            return {};
        }else if(nums.size() == 1){
            return {{nums[0]}};
        }else{
            func(nums,vec,choice);
            return ans;
        }
    }
};

Leetcode784. 字母大小写全排列

class Solution {
public:
vector<string> letterCasePermutation(string S) {
        vector<string> ans;
        if(S.empty()) return ans;
        dfs(S, 0, ans);
        return ans;
    }

    void dfs(string &str, int index, vector<string> &ans){
        if(index == str.size()){
            ans.push_back(str);
            return;
        }
        if(isdigit(str[index])) dfs(str, index+1, ans);
        else{
            dfs(str, index+1, ans);
            if(isupper(str[index])){
                str[index] = tolower(str[index]);
                dfs(str, index+1, ans);
                str[index] = toupper(str[index]);
            }else{
                str[index] = toupper(str[index]);
                dfs(str, index+1, ans);
                str[index] = tolower(str[index]);
            }
        }
    }
};

你可能感兴趣的:(算法,dfs,leetcode,hash,算法)