Skip to content

Commit 1441ec8

Browse files
committed
Signed-off-by: yuduozhou <[email protected]>
1 parent d6c8f2b commit 1441ec8

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

UniqueBST.java

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
public class Solution {
2+
public int numTrees(int n) {
3+
// Start typing your Java solution below
4+
// DO NOT write main() function
5+
if (n <= 1) return 1;
6+
int result = 0;
7+
for (int i = 1; i <= n ; i++){
8+
result += numTrees(i - 1) * numTrees(n - i);
9+
}
10+
return result;
11+
}
12+
}

UniqueBST_II.java

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
public class Solution {
2+
public ArrayList<TreeNode> generateTrees(int n) {
3+
// Start typing your Java solution below
4+
// DO NOT write main() function
5+
return getTrees(1, n);
6+
}
7+
public ArrayList<TreeNode> getTrees(int min, int max){
8+
ArrayList<TreeNode> result = new ArrayList<TreeNode>();
9+
if (min > max){
10+
result.add(null);
11+
return result;
12+
}
13+
for (int root = min; root <= max; root ++){
14+
ArrayList<TreeNode> lefts = getTrees(min, root - 1);
15+
ArrayList<TreeNode> rights = getTrees(root + 1, max);
16+
for (int i = 0; i < lefts.size(); i++ ){
17+
for (int j = 0; j < rights.size(); j ++){
18+
TreeNode rootNode = new TreeNode(root);
19+
rootNode.right = rights.get(j);
20+
rootNode.left = lefts.get(i);
21+
result.add(rootNode);
22+
}
23+
}
24+
}
25+
return result;
26+
}
27+
}

UniquePaths.java

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/* numeric theory */
2+
public class Solution {
3+
public int uniquePaths(int m, int n) {
4+
// Start typing your Java solution below
5+
// DO NOT write main() function
6+
if (-- m > -- n){
7+
int temp = m;
8+
m = n;
9+
n = temp;
10+
}
11+
long denominator = 1, numerator = 1;
12+
for (int i = 1; i <= m; i++)
13+
denominator *= i;
14+
for (int i = m + n; i > n; i --)
15+
numerator *= i;
16+
return (int) (numerator / denominator);
17+
}
18+
}
19+
20+
/* DP */
21+
public class Solution {
22+
public int uniquePaths(int m, int n) {
23+
// Start typing your Java solution below
24+
// DO NOT write main() function
25+
int[][] table = new int[m][n];
26+
table[0][0] = 1;
27+
for (int i = 1; i < m; i ++){
28+
table[i][0] = table[i - 1][0];
29+
}
30+
for (int j = 1; j < n; j ++){
31+
table[0][j] = table[0][j - 1];
32+
}
33+
for (int i = 1; i < m; i ++){
34+
for (int j = 1; j < n; j ++){
35+
table[i][j] = table[i][j - 1] + table[i - 1][j];
36+
}
37+
}
38+
return table[m - 1][n - 1];
39+
}
40+
}

0 commit comments

Comments
 (0)