1. 程式人生 > >n個括號對的所有可能情況

n個括號對的所有可能情況

括號 main color 思路 出棧 gin col r+ div

所有可能情況的數量為卡特蘭數。故求所有可能的出棧情況與此類似。

思路:

若左括號沒全插入,則插入左括號;

若已插入左括號數比已插入右括號數多,則插入右括號;

 1 #include<stdio.h>
 2 void printParen(int l,int r,int n,char str[],int index)
 3 {
 4     if(l>n || r<0 || l<r)return;//已插入的右括號比左括號多,不合法括號對 
 5     
 6     if(l==n && r==n) printf("%s\n",str);
7 else 8 {//已插入的左括號不比已插入的右括號少 9 if(l<n) 10 {//若左括號沒插入完,繼續插入左括號 11 str[index]=(; 12 printParen(l+1,r,n,str,index+1); 13 } 14 if(l>r) 15 {//若已插入的左括號比右括號多,插入右括號 16 str[index]=); 17 printParen(l,r+1
,n,str,index+1); 18 } 19 } 20 } 21 int main() 22 { 23 static int count=3; 24 char str[2*count+1]; 25 str[2*count]=\0; 26 printParen(0,0,count,str,0); 27 return 0; 28 }

n個括號對的所有可能情況