a229: 括號匹配問題
出處 : http://zerojudge.tw/ShowProblem?problemid=a229
Content :
最近要開學了! ( ~~~ 跟題目沒有什麼關係 ) ><
請寫一個程式把所有合法括號匹配方式列出來!
Ex. (()) , ((()())) , ()((())) 是合法的匹配方式
)( , (()))( , ()(()( 是不合法的匹配方式
合法匹配的括號 , 從答案列的開頭到答案列某一點,左括弧次數永遠大於等於右括弧!
Ex. 合法匹配 ((()()))
字串 ( 左括弧 : 1 >= 右括弧 : 0
字串 (( 左括弧 : 2 >= 右括弧 : 0
字串 ((( 左括弧 : 3 >= 右括弧 : 0
字串 ((() 左括弧 : 3 >= 右括弧 : 1
字串 ((()( 左括弧 : 4 >= 右括弧 : 1
字串 ((()() 左括弧 : 4 >= 右括弧 : 2
字串 ((()()) 左括弧 : 4 >= 右括弧 : 3
字串 ((()())) 左括弧 : 4 >= 右括弧 : 4
Ex. 不合法匹配 (()))(
字串 ( 左括弧 : 1 >= 右括弧 : 0
字串 (( 左括弧 : 2 >= 右括弧 : 0
字串 (() 左括弧 : 2 >= 右括弧 : 1
字串 (()) 左括弧 : 2 >= 右括弧 : 2
字串 (())) 左括弧 : 2 <= 右括弧 : 3
!!! 右括弧次數大於左括弧了! (()))( 為不合法匹配
Input :
輸入一個正整數 N , 1 =< N <= 13 。
N 代表有幾組括號要匹配
Ex.
N = 1 代表 一組括號 ()
N = 2 代表有兩組括號 ()()
Output :
輸出 N 組括號的所有合法匹配組合
輸出方式請見範例
Sample Input :
1
2
3
4
Sample Output :
()
(())
()()
((()))
(()())
(())()
()(())
()()()
(((())))
((()()))
((())())
((()))()
(()(()))
(()()())
(()())()
(())(())
(())()()
()((()))
()(()())
()(())()
()()(())
()()()()
Hint :
背景知識:
2011 / 8 / 27 11 : 50 測資修正
通過時間改為 1s
Author :
(管理:stanley17112000)
解題策略
遞迴求解。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <iostream>#include <deque>#include <cstdio>using namespace std; deque <char> qu; int num; void pa(int,int,int); int main(){ while(cin >> num){ pa(0,0,0); cout <<endl; } } void pa(int le,int ri,int n){ if (n==2*num){//終止遞迴 for(int i=0;i<2*num;i++) printf("%c",qu[i]); printf("\n"); return; } if (le<num) {//le表示已經加入的左小括號個數,從0開始不能超過或等於num qu.push_back('('); pa(le+1,ri,n+1);//多了一個左小括號le+1,n+1為已經加入的左與右小括號個數 qu.pop_back(); } if ((le>ri)&&(ri<num)) {//左小括號要大於右小括號數,且右小括號數要小於num qu.push_back(')'); pa(le,ri+1,n+1);//多了一個右小括號ri+1,n+1為已經加入的左與右小括號個數 qu.pop_back(); } }