my version for each round i `buf[x]` means **the number of trees** that has `x` right nodes base on the `buf` vector of the `i - 1` round, we can calculate the `buf` of the `i` round: since the element now add is `cur_n + 1` which is the largest element so far,
| 18 | // since the element now add is `cur_n + 1` which is the largest element so far, |
| 19 | // |
| 20 | int numTrees(int n) { |
| 21 | const int len = 1 << 10; |
| 22 | vector<int> buf (len, 0); |
| 23 | vector<int> add (len, 0); |
| 24 | buf[1] = 1; |
| 25 | for (int cur_n = 1; cur_n < n; cur_n ++) { // now at state cur_n --> state cur_n + 1 |
| 26 | for (int p = 1; p <= cur_n; p ++) // --> previus buf vector |
| 27 | for (int c = 1; c <= p + 1; c ++) // --> current add vector |
| 28 | if (c != p) |
| 29 | add[c] += buf[p]; |
| 30 | for (int _ = 1; _ <= cur_n + 1; _ ++) { |
| 31 | buf[_] += add[_]; |
| 32 | add[_] = 0; // clear the previous `add` vector |
| 33 | } |
| 34 | // now (cur_n + 1) state done |
| 35 | } |
| 36 | int res = 0; |
| 37 | for (int i=1; i<=n; i++) |
| 38 | res += buf[i]; |
| 39 | return res; |
| 40 | } |
| 41 | |
| 42 | // dp thought O(n) time O(n) space |
| 43 | int numTrees_dp(int n) { |
nothing calls this directly
no outgoing calls
no test coverage detected