File tree 4 files changed +63
-1
lines changed
4 files changed +63
-1
lines changed Original file line number Diff line number Diff line change 1
- // Multiply Strings
1
+ // Multiply Strings
2
+ // we should know how to add two strings together:
Original file line number Diff line number Diff line change
1
+ // Unique Binary Search Trees
2
+ // f(0) = 1 empty tree
3
+ // f(1) = 1 root
4
+ // f(2) = f(0) * f(1) // 1 as root
5
+ // + f(1) * f(0) // 2 as root
6
+ // f(3) = f(0) * f(2) // 1 as root
7
+ // + f(1) * f(1) // 2 s root
8
+ // + f(2) * f(0) // 3 as root
9
+ // ==> f(i) = sum(f(k - 1) * f(i - k)) ( k = 1 to i)
10
+
11
+ class Solution {
12
+ public:
13
+ int numTrees (int n) {
14
+ vector<int > f (n + 1 , 0 );
15
+ f[0 ] = 1 ;
16
+ f[1 ] = 1 ;
17
+ for (int i = 2 ; i <= n; i++){
18
+ for (int k = 1 ; k <= i; k++){
19
+ f[i] += f[k - 1 ] * f[i - k];
20
+ }
21
+ }
22
+ return f[n];
23
+ }
24
+ };
Original file line number Diff line number Diff line change
1
+ // Unique Paths
2
+ // p[i][j] is from[0][0] to i, j
3
+ // p[i][j] = p[i-1][j] + p[i][j-1];
4
+ class Solution {
5
+ public:
6
+ int uniquePaths (int m, int n) {
7
+ int p[m][n];
8
+ for (int i=0 ; i < m; i++){
9
+ p[i][0 ] = 1 ;
10
+ }
11
+ for (int i=0 ; i < n; i++){
12
+ p[0 ][i] = 1 ;
13
+ }
14
+ for (int i = 1 ; i < m; i++){
15
+ for (int j = 1 ; j < n; j++){
16
+ p[i][j] = p[i-1 ][j] + p[i][j-1 ];
17
+ }
18
+ }
19
+ return p[m-1 ][n-1 ];
20
+ }
21
+ };
Original file line number Diff line number Diff line change
1
+
2
+ // bottom-up regular method
3
+ // it could be O(1) space complexcity
4
+ class Solution {
5
+ public:
6
+ int minimumTotal (vector<vector<int > > &triangle) {
7
+ int n = triangle.size ();
8
+ if (n == 0 ) return 0 ;
9
+ for (int i = n - 2 ; i >= 0 ; i--){
10
+ for (int j = 0 ; j <= i; j++){
11
+ triangle[i][j] = min (triangle[i+1 ][j], triangle[i+1 ][j+1 ]) + triangle[i][j];
12
+ }
13
+ }
14
+ return triangle[0 ][0 ];
15
+ }
16
+ };
You can’t perform that action at this time.
0 commit comments