This is a BST(binary search tree) numbers counting problem but solved in dynamic programing.
https://discuss.leetcode.com/category/104/unique-binary-search-trees
This solution really gives me a shock. Before solving u need do some mathematical deduce in papers and get the dp function, which fantistically!
class Solution { public: int numTrees(int n) { int G[100]; for(int i = 0; i <= n; i ++) G[i] = 0; G[0] = G[1] = 1; for(int i = 2; i <= n; i ++){ for(int j = 1; j <= i; j ++) G[i] += G[j - 1] * G[i - j]; } return G[n]; } };
时间: 2024-10-16 01:46:38