leetcode backtracking algorithm - the basis of difficulty

Are direct dfs, be it to consolidate

Monogram phone number

Given a string contains only numeric characters 2-9, it can return all letter combinations indicated.

Given digital map to letters as follows (the same telephone key). Note 1 does not correspond to any alphabet.

image

Thinking

Has been searched, to the finish judge whether there have been, it did not appear then to the collection

Code

class Solution {
    set<string>s;
    map<char,string>m;
public:
    
    void dfs(string d, string cur, int step){
        if(step>d.size()){
            return;
        }
        if(step==d.size()){
            if(s.count(cur)>0){
                return;
            }else{
                s.insert(cur);
            }
        }
        string tmp=m[d[step]];
        for(int i=0;i<tmp.size();++i){
            dfs(d,cur+tmp[i],step+1);
        }
    }
    
    vector<string> letterCombinations(string digits) {
        m.insert(make_pair('2',"abc"));
        m.insert(make_pair('3',"def"));
        m.insert(make_pair('4',"ghi"));
        m.insert(make_pair('5',"jkl"));
        m.insert(make_pair('6',"mno"));
        m.insert(make_pair('7',"pqrs"));
        m.insert(make_pair('8',"tuv"));
        m.insert(make_pair('9',"wxyz"));
        string s1;
        vector<string>ans;
        if(digits.size()==0){
            return ans;
        }
        dfs(digits,s1,0);
        for(auto i = s.begin(); i!=s.end();++i){
            ans.push_back(*i);
        }
        return ans;
    }
};

Generates brackets

N represents the number of generation is given in parentheses, you write a function, it is possible to generate all possible combinations of brackets and effective.

For example, given n = 3, to generate the result is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

Thinking

The first is certainly left parenthesis, followed by the search, each location may be "(" or ")", pay attention to the relationship between the number of left and right parentheses search

Code

class Solution {
    vector<string>ans;
    bool ok(const string&s){
        stack<char>st;
        for(int i=0;i<s.size();++i){
            if(s[i]=='('){
                st.push(s[i]);
            }else{
                if(st.empty()){
                    return false;
                }else{
                    char c=st.top();
                    if(c!='(')return false;
                    else st.pop();
                }
            }
        }
        return st.empty();
    }
public:
    void dfs(string cur,int L,int R,int total){
        if(L+R>total)return;
        if(abs(L-R)>total-L-R)return;
        if(L+R==total){
            if(L!=R){
                return;
            }else{
                if(ok(cur)){
                    ans.push_back(cur);   
                }
                return;
            }
        }
        dfs(cur+'(',L+1,R,total);
        dfs(cur+')',L,R+1,total);
    }
    vector<string> generateParenthesis(int n) {
        if(n==0)return ans;
        dfs("(",1,0,2*n);
        return ans;
    }
};

Full array

Given a sequence of numbers is not repeated, all possible return to full permutation.

Example:

Input: [1,2,3]
Output:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

Thinking

dfs, with the next element of the array to the record you have accessed
the method is also effective for duplicate elements

Code

class Solution {
public:
    void dfs(int step,vector<int>cur,vector<int>&nums,int*vis,vector<vector<int>>&ans){
        if(step>nums.size())return;
        if(step==nums.size()){
            ans.push_back(cur);
            return;
        }
        for(int i=0;i<nums.size();++i){
            if(!vis[i]){
                vis[i]=1;
                cur.push_back(nums[i]);
                dfs(step+1,cur,nums,vis,ans);
                vis[i]=0;
                cur.pop_back();
            }
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> ans;
        if(nums.size()==0)return ans;
        int vis[nums.size()];
        memset(vis,0,sizeof(vis));
        vector<int>tmp;
        dfs(0,tmp,nums,vis,ans);
        return ans;
    }
};

Child Collection

Given a set of no repeating element integer array nums, which returns an array of all possible subsets (power set).

Description: Solution Set can not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

Thinking

With whole arrangement is very similar, but can not be repeated ([1,2] and [2,1] is a subset of the same)
so that the search range is limited after the left, i.e. only from large to small ([1,2], [1,3], [2,3])
so as not to repeat

Code

class Solution {
public:
    void dfs(int step, vector<int> cur,int left,int*vis, int limit,const vector<int>&nums, vector<vector<int>>&ans){
        if(step>limit)return;
        if(step==limit){
            ans.push_back(cur);
            return;
        }
        for(int i=left;i<nums.size();++i){
            if(!vis[i]){
                vis[i]=1;
                cur.push_back(nums[i]);
                dfs(step+1,cur,i+1,vis,limit,nums,ans);
                cur.pop_back();
                vis[i]=0;
            }
        }
    }
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> ans;
        vector<int>emp;
        ans.push_back(emp);
        int vis[nums.size()];
        if(nums.size()==0)return ans;
        for(int i=1;i<=nums.size();++i){
            memset(vis,0,sizeof(vis));
            dfs(0,emp,0,vis,i,nums,ans);
        }
        return ans;
    }
};

Word Search

Given a two-dimensional grid and a word, to find out whether the word exists in the grid.

Words must, by the letters in adjacent cells constituting alphabetically, where "adjacent" cells that are adjacent horizontally or vertically adjacent cells. Letters within the same cell is not allowed to be reused.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.

Thinking

The first is no turning back, then each dfs the current location mark (you can use an array of flags)
here I assigned directly to the board '', note dfs finished restore the original value
every step of comparing the current position of the judge and cross-border character is equal to the word the character corresponding to the position
after finding the global flag is set to true, do useful work to prevent

Code

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        this->board=board;
        this->word=word;
        this->mx=board.size();
        this->my=board[0].size();
        this->find=false;
        for(int i=0;i<mx;++i){
            for(int j=0;j<my;++j){
                if(dfs(i,j,0))return true;
            }
        }
        return false;
    }
private:
    bool dfs(int x,int y, int cur){
        if(cur==this->word.size()){
            this->find=true;
            return true;
        }
        if(x<0||x>=this->mx||y<0||y>=this->my||this->board[x][y]!=this->word[cur]){
            return false;
        }
        if(find){
            return true;
        }
        char tmp=board[x][y];
        board[x][y]=' ';
        if(dfs(x-1,y,cur+1)||dfs(x,y-1,cur+1)||dfs(x,y+1,cur+1)||dfs(x+1,y,cur+1)){
            find=true;
            board[x][y]=tmp;
            return true;
        }
        board[x][y]=tmp;
        return false;
    }
    vector<vector<char>>board;
    string word;
    int mx,my;
    bool find;
};

Guess you like

Origin www.cnblogs.com/dionysun/p/12019692.html