Leetcode题解(递归和回溯)

Leetcode_17

题目描述

见官网

c++

    #include 
    #include 
    #include 
    #include 

    using namespace std;

    /// Backtracking
    /// Time Complexity: O(2^len(s))
    /// Space Complexity: O(len(s))
    class Solution {

    private:
        const string letterMap[10] = {
                " ",    //0
                "",     //1
                "abc",  //2
                "def",  //3
                "ghi",  //4
                "jkl",  //5
                "mno",  //6
                "pqrs", //7
                "tuv",  //8
                "wxyz"  //9
        };

        vector<string> res;

        void findCombination(const string &digits, int index, const string &s){

            if(index == digits.size()){
                res.push_back(s);
                return;
            }

            char c = digits[index];
            assert(c >= '0' && c <= '9' && c != '1');
            string letters = letterMap[c - '0'];
            for(int i = 0 ; i < letters.size() ; i ++)
                findCombination(digits, index+1, s + letters[i]);

            return;
        }

    public:
        vector<string> letterCombinations(string digits) {

            res.clear();
            if(digits == "")
                return res;

            findCombination(digits, 0, "");

            return res;
        }
    };


    void printVec(const vector<string>& vec){
        for(string s: vec)
            cout << s << endl;
    }

    int main() {

        printVec(Solution().letterCombinations("234"));

        return 0;
    }

java

    #include 
    #include 
    #include 
    #include 

    using namespace std;

    /// Backtracking
    /// Time Complexity: O(2^len(s))
    /// Space Complexity: O(len(s))
    class Solution {

    private:
        const string letterMap[10] = {
                " ",    //0
                "",     //1
                "abc",  //2
                "def",  //3
                "ghi",  //4
                "jkl",  //5
                "mno",  //6
                "pqrs", //7
                "tuv",  //8
                "wxyz"  //9
        };

        vector<string> res;

        void findCombination(const string &digits, int index, const string &s){

            if(index == digits.size()){
                res.push_back(s);
                return;
            }

            char c = digits[index];
            assert(c >= '0' && c <= '9' && c != '1');
            string letters = letterMap[c - '0'];
            for(int i = 0 ; i < letters.size() ; i ++)
                findCombination(digits, index+1, s + letters[i]);

            return;
        }

    public:
        vector<string> letterCombinations(string digits) {

            res.clear();
            if(digits == "")
                return res;

            findCombination(digits, 0, "");

            return res;
        }
    };


    void printVec(const vector<string>& vec){
        for(string s: vec)
            cout << s << endl;
    }

    int main() {

        printVec(Solution().letterCombinations("234"));

        return 0;
    }

Leetcode_46

#include 
#include 
using namespace std;

class Solution {
private:
    vector<vector<int>> res;
    vector<bool> used;
    void generatePermutation(const vector<int>& nums, int index, vector<int>& p)
    {
        if(index == nums.size())
        {
            res.push_back(p);
            return;
        }
        for(int i = 0; iif(!used[i]){
                used[i] = true;
                p.push_back(nums[i]);
                generatePermutation(nums,index+1,p);
                p.pop_back();
                used[i] = false;       

            }

        }
        return;

    }
public:
    vector<vector<int>> permute(vector<int>& nums) {
        res.clear();
        if(nums.size()==0)
            return res;
        used = vector<bool>(nums.size(), false);
        vector<int> p;
        generatePermutation(nums,0,p);
        return res;

    }
};


void printVec(const vector<int>& vec){
    for(int e: vec)
        cout << e << " ";
    cout << endl;
}

int main() {

    int nums[] = {1, 2, 3};
    vector<int> vec(nums, nums + sizeof(nums)/sizeof(int) );

    vector<vector<int>> res = Solution().permute(vec);
    for(int i = 0 ; i < res.size() ; i ++)
        printVec(res[i]);

    return 0;
}

Leetcode_77

组合问题

#include 
#include 
using namespace std;
class Solution {
private:
    vector<vector<int>> res;
    void generateCombinations(int n, int k, int start, vector<int> &c)
    {
        if(c.size() == k)
        {
            res.push_back(c);
            return;
        }
        for(int i = start;i<=n;i++){
            c.push_back(i);
            generateCombinations(n,k,i+1,c);
            c.pop_back();
        }
        return;

    }
public:
    vector<vector<int>> combine(int n, int k) {
        res.clear();
        if(n <= 0 || k<=0 || k>n)
            return res;

        vector<int> c;
        generateCombinations(n,k,1,c);
        return res;

    }
};


void printVec(const vector<int>& vec){

    for(int e: vec)
        cout << e << " ";
    cout << endl;
}

int main() {

    vector<vector<int>> res = Solution().combine(4,2);
    for( int i = 0 ; i < res.size() ; i ++ )
        printVec(res[i]);
    return 0;
}

Leetcode_79

#include 
#include 
using namespace std;

class Solution {
private:
    int m,n;
    vector<vector<bool>> visited;
    int d[4][2] = {{-1, 0}, {0,1}, {1, 0}, {0, -1}};

    bool inArea( int x , int y ){
        return x >= 0 && x < m && y >= 0 && y < n;
    }


    //start from board[startx][starty], find word[index...word.size())
    bool searchWord( const vector<vector<char>> &board, const string& word, int index,
                    int startx, int starty )
    {
        if(index == word.size()-1)
            return board[startx][starty] == word[index];
        if(board[startx][starty] == word[index])
        {
            visited[startx][starty] = true;
            for(int i = 0;i<4;i++)
            {
                int newx = startx+d[i][0];
                int newy = starty+d[i][1];
                if(inArea(newx,newy)&&!visited[newx][newy]&&searchWord(board,word,index+1,newx,newy))
                    return true;

            }
            visited[startx][starty] = false;
        }
        return false;
    }

public:
    bool exist(vector<vector<char>>& board, string word) {
        m = board.size();
        assert( m > 0 );
        n = board[0].size();
        visited = vector<vector<bool>>(m, vector<bool>(n, false));
        for(int i = 0; ifor(int j = 0; jif(searchWord(board,word,0,i,j))
                    return true;
        return false;

    }
};


int main() {

    char b1[3][4] = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
    vector<vector<char>> board1;
    for( int i = 0 ; i < 3 ; i ++ )
        board1.push_back(vector<char>(b1[i], b1[i] + sizeof(b1[i]) / sizeof(char)));

    int cases = 3;
    string words[3] = {"ABCCED" , "SEE" , "ABCB" };
    for( int i = 0 ; i < cases ; i ++ )
        if(Solution().exist(board1,words[i]))
            cout<<"found "<else
            cout<<"can not found "<// ---

    char b2[1][1] = {{'A'}};
    vector<vector<char>> board2;
    for(int i = 0 ; i < 3 ; i ++)
        board2.push_back(vector<char>(b2[i],b2[i]+sizeof(b2[i])/sizeof(char)));

    if(Solution().exist(board2,"AB"))
        cout<<"found AB"<else
        cout<<"can not found AB"<return 0;
}

你可能感兴趣的:(编码)