LetCode의 귀속 문제 (2)

4846 단어 LeetCode귀속
1. Generate Parenthesis
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()"
전형적인 귀속.한 걸음 한 걸음 문자열을 구성합니다.왼쪽 괄호가 // void CombinationPare(vector<string> &result, string &sample, int deep, int n, int left, int right){ if(deep == 2*n){ result.push_back(sample); return; } if(left<n){ sample.push_back('('); CombinationPare(result,sample,deep+1,n,left+1,right); sample.resize(sample.size()-1); } if(right<left){ sample.push_back(')'); CombinationPare(result,sample,deep+1,n,left,right+1); sample.resize(sample.size()-1); } } vector<string> generateParenthesis(int n) { vector<string> result; string sample; if(n>0){ CombinationPare(result,sample,0,n,0,0); } return result; }
2. N-Queens
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where  'Q'  and  '.'  both indicate a queen and an empty space respectively.
For example, There exist two distinct solutions to the 4-queens puzzle:
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

Analysis: The classic recursive problem. 1. Use a int vector to store the current state,  A[i]=j refers that the ith row and jth column is placed a queen. 2. Valid state:  not in the same column, which is A[i]!=A[current], not in the same diagonal direction: abs(A[i]-A[current]) != r-i 3. Recursion:         Start:   placeQueen(0,n)         if current ==n then print result         else             for each place less than n,                  place queen                 if current state is valid, then place next queen   place Queen(cur+1,n)            end for         end i
void printQueen(vector<int> &A,int n,vector<vector<string>> &result){
    vector<string> r;
        for(int i=0;i<n;i++){
            string str(n,'.');
            str[A[i]] = 'Q';
            r.push_back(str);
        }
        result.push_back(r);
}
bool isValidQueens(vector<int>A,int r){
    for(int i=0;i<r;i++){
        if((A[i]==A[r])||(abs(A[i]-A[r]))==(r-i))
            return false;
    }
    return true;
}
void nqueens(vector<int> A,int cur, int n,vector<vector<string>> &result){
    if(cur == n){
        printQueen(A,n,result);
    }else{
        for(int i=0;i<n;i++){
            A[cur] = i;
            if(isValidQueens(A,cur))
                nqueens(A,cur+1,n,result);
        }
    }
}
vector<vector<string> > solveNQueens(int n) {
    vector<vector<string>> result;
    result.clear();
    vector<int> A(n,-1);
    nqueens(A,0,n,result);
    return result;
}

3. N-Queens 2
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Analysis:
Same idea just a little bit difference from the previous one.
Note:
If I use the vector as the data structure, the code cannot pass the large online judge, however, if I use the dynamic array, which successfully pass all the online judge test. If we use the vector like the below code shows, should use reference vector &A instead of vector A to avoid necessary vector copy. 
bool isValidQueens(vector<int> &A,int r){
    for(int i=0;i<r;i++){
        if((A[i]==A[r])||(abs(A[i]-A[r]))==(r-i))
            return false;
    }
    return true;
}
    void nqueens2(int n, int &result, int cur, vector<int> &A){
    if(cur == n){
        result++;
        return;
    }else{
        for(int i=0;i<n;i++){
            A[cur] = i;
            if(isValidQueens(A, cur))
                nqueens2(n,result,cur+1,A);
        }
    }
}
int totalNQueens(int n) {
    int result =0;
    vector<int> A(n,-1);
    nqueens2(n,result,0,A);
    return result;

}

좋은 웹페이지 즐겨찾기