形成山脉的方法数

问题描述

我正在研究加泰罗尼亚数字的应用:

形成“山脉”的方法数,其中 n 个上行和 n 个下行都保持在原始线以上。

enter image description here

现在给定一个数字 n,找出山脉的数量。

public int countMountainRanges(int n) {

}

我们可以在这里使用什么逻辑或公式来获取输入 n 的方式数。

我尝试了公式 F(n) = F(n-1) + F(n-2),但在这种情况下不起作用。

解决方法

F(n) = F(n-1) + F(n-2) 是第 n 个斐波那契数的公式。另一方面,第 n 个加泰罗尼亚数由 (2n select n) / (n + 1) 给出。

public static int countMountainRanges(int n) {
    return choose(2 * n,n) / (n + 1);
}
private static int choose(int n,int k){
    int res = 1;
    k = Math.min(k,n - k);
    for (int i = 0; i < k; i++) {
        res = res * (n - i) / (i + 1);
    }
    return res;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...