*LeetCode-Unique Binary Search Trees

来源:互联网 发布:pci串行端口 感叹号 编辑:程序博客网 时间:2024/05/21 05:08

卡特兰数的应用之一,还有一个是让求有多少种方式配对括号。

http://en.wikipedia.org/wiki/Catalan_number

这个题发现对于每个数字n 解法数=左子树0个结点的方法 * 右子树n-1个节点的方法 + 左1个节点*右子n-2个.......

要注意的是要多存一个arr[0] = 1 数组是n+1大小的

public class Solution {    public int numTrees(int n) {        if ( n <= 0 )            return 0;        int [] arr = new int [n+1];        arr[0] = 1;        for ( int i = 1; i < n+1; i++ ){            for ( int j = 0; j < i; j ++){                arr[i] += arr[j]*arr[i-j-1];            }        }        return arr[n];    }}


0 0
原创粉丝点击