1. 程式人生 > >[leetcode]96. Unique Binary Search Trees

[leetcode]96. Unique Binary Search Trees

[leetcode]96. Unique Binary Search Trees


Analysis

intern intern intern—— [每天刷題並不難0.0]

Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?
在這裡插入圖片描述
動態規劃解決,狀態轉移方程:
DP[n] = DP[0]DP[n-1]+DP[1]DP[n-2]+…+DP[i-1]DP[n-i]+…DP[n-1]DP[0];

Implement

class Solution
{ public: int numTrees(int n) { vector<int> DP(n+1, 0); DP[0] = DP[1] = 1; for(int i=2; i<=n; i++){ for(int j=1; j<=i; j++) DP[i] += DP[j-1]*DP[i-j]; } return DP[n]; } };