【Leetcode】之Unique Binary Search Trees

来源:互联网 发布:mongodb 数据库设计 编辑:程序博客网 时间:2024/05/21 19:40

一.问题描述

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

For example,
Given n = 3, there are a total of 5 unique BST's.

   1         3     3      2      1    \       /     /      / \      \     3     2     1      1   3      2    /     /       \                 \   2     1         2                 3

二.我的解题思路

对于这样的题目,首先自然是分析问题。如果让我去做这个问题,我会以根元素作为出发点,对于从1-n的每一个元素,都可以作为根节点。确定根节点i之后,自然左子树应该放1...i-1(T(I-1))、右子树应该放i+1...n(T(n-i))。这样就能写出递归关系了。

但是如果直接用分治递归做会有很多重复的子问题,所以对本题适合采用动态规划的算法思想。测试通过的程序如下:

class Solution {public:    int numTrees(int n) {        int * tmp = new int[n+1];        tmp[0]=1;tmp[1]=1;tmp[2]=2;        int i=3;        int res;        while(i<=n){            tmp[i]=0;            for(int j=1;j<=i;j++)                tmp[i]+=tmp[i-j]*tmp[j-1];                    i++;                }        return tmp[n];    }};


0 0
原创粉丝点击