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:

"((()))", "(()())", "(())()", "()(())", "()()()"

典型的递归。一步步构造字符串。当左括号出现次数<n时,就可以放置新的左括号。当右括号出现次数小于左括号出现次数时,就可以放置新的右括号。

//
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;

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值