LetCode의 귀속 문제 (2)
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;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 문자열 입력으로 모든 유효한 IP 주소 생성(LeetCode 93번 문제)이 문제의 공식 난이도는 Medium으로 좋아요 1296, 반대 505, 통과율 35.4%를 눌렀다.각 항목의 지표로 말하자면 보기에는 약간 규범에 맞는 것 같지만, 실제로도 확실히 그렇다.이 문제의 해법과 의도는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.