方法一:(深搜、递归)
package suanfa_xiaoqiang1;
import java.util.Scanner;
public class P1044 {
static long[][] f=new long[20][20];
static int n;
//f[x][y]是表示当操作队列里还有x个,栈里有y个的时候有几种方案
public static long dfs(int x,int y) {
if (f[x][y]!=0) return f[x][y]; //记忆化
if(x==0) return 1; //队列没有了
if(y>0) f[x][y]+=dfs(x, y-1); //栈不为空
f[x][y]+=dfs(x-1, y+1);
return f[x][y]; //返回方案值
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
System.out.println(dfs(n,0));
}
}
方法二:(动态规划、递推)
package suanfa_xiaoqiang1;
import java.util.Scanner;
public class P1044 {
static long[][] f=new long[20][20];
static int n;
//f[x][y]是表示当操作队列里还有x个,栈里有y个的时候有几种方案
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
for (int j = 0; j <= n; j++) {
f[0][j]=1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if(i==j) f[i][j]=f[i-1][j];
else f[i][j]=f[i][j-1]+f[i-1][j];
}
}
System.out.println(f[n][n]);
}
}
方法三:(公式)卡特兰数
package suanfa_xiaoqiang1;
import java.util.Scanner;
public class P1044 {
static long[] f=new long[20];
static int n;
//f[x][y]是表示当操作队列里还有x个,栈里有y个的时候有几种方案
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
f[0]=1;
f[1]=1;
for (int i = 2; i <= n; i++) {
for (int j = 0; j < i; j++) {
f[i]=f[i]+f[j]*f[i-j-1];
}
}
System.out.println(f[n]);
}
}
递归和递推的区别:https://blog.csdn.net/weixin_44143702/article/details/86551826