aboutsummaryrefslogtreecommitdiff
path: root/unique_bst.c
blob: 2e1ffad72b0be4ebb90b62e70e4f695fa186342b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 96. Unique Binary Search Trees
#include <stdio.h>

/*
 * given an integer 'n', return the number of structurally unique BST's which
 * has exactly 'n' nodes of unique values from 1 to 'n'
 */

int numTrees(int n) {
  int rem[n + 1];
  if (!n)
    return 1;
  if (n == 1 || n == 2)
    return n;
  rem[0] = 1;
  rem[1] = 1;
  rem[2] = 2;
  for (int i = 3; i <= n; i++) {
    rem[i] = 0;
    for (int j = 1; j <= i; j++)
      rem[i] = rem[i] + rem[i - j] * rem[j - 1];
  }
  return rem[n];
}

int main() {
  printf("%d\n", numTrees(3)); // expect: 5
  printf("%d\n", numTrees(1)); // expect: 1
}