Question about the number of matching brackets in Huawei OJ training, Huawei oj
The questions are as follows:
Parentheses matching
Input n parentheses and output n parentheses that can be combined. For example --
Only () is input;
When the input is 2, there are two types: () and;
When 3 is input, there are (), () and ((())), five types.
There are 14 input values .. And so on.
I think of stupid methods, and so on, because I believe there must be a formula. After a while. I did not summarize it, so I read the book because I have read similar questions in my impressions.
Then the formula is found. Haha.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); scanner.close(); if (n == 0) { System.out.println(0);}else{ System.out.println((int) (jiecheng(2 * n) / (jiecheng(n) * jiecheng(n) * (n + 1)))); } } private static long jiecheng(int n) { long result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } }
Brackets matching
# Include <stdio. h>
# Deprecision MAX 100
Int match (char * str)
{
Char stack [MAX], * p = stack;
While (* str)
{
Switch (* str)
{
Case '(':
{
* P ++ = * str;
Break;
}
Case ')':
{
If (* -- p! = '(')
Return 0;
Break;
}
Case '[':
{
* P ++ = * str;
Break;
}
Case ']':
{
If (* -- p! = '[')
Return 0;
Break;
}
Case '{':
{
* P ++ = * str;
Break;
}
Case '}':
{
If (* -- p! = '{')
Return 0;
Break;
}
}
Str ++;
}
If (stack = p)
Return 1;
Else
Return 0;
}
Int main ()
{
Char str [MAX];
Gets (str );
If (match (str ))
{
Printf ("match \ n ");
}
Else
{
Printf ("not match \ n ");
}
Return 0;
}
Brackets matching
# Include <stdio. h>
# Include <string. h>
# Define Max size 1000
Typedef char datatype;
Typedef struct
{
Datatype s [MAXSIZE];
Int top;
} Stack;
Void init (stack * s)
{
S-> top = 0;
}
Void push (stack * s, datatype c)
{
S-> s [s-> top ++] = c;
}
Int empty (stack * s)
{
Return s-> top = 0;
}
Datatype pop (stack * s)
{
If (! Empty (s ))
Return s-> s [-- s-> top];
Return 0;
}
Int main ()
{
Stack s;
Char input [1000];
Int len, OK, I;
Char temp;
While (gets (input ))
{
OK = 1;
Init (& s );
Len = strlen (input );
For (I = 0; OK & I <len; I ++)
{
Switch (input [I])
{
Case '(':
Case '[':
Case '{':
Push (& s, input [I]); break;
Case ')':
Temp = pop (& s );
If (temp! = '(')
OK = 0;
Break;
Case ']':
Temp = pop (& s );
If (temp! = '[')
... The remaining full text>