http://zhangnai.xin/2016/09/20/LeetCode-Framework/java
目錄結構:算法
- LeetCode ——項目名稱,方便Eclipse內置Git對代碼進行管理和多終端同步
- pid1 ——題目包,每一個題目封裝在一個單獨的包中,包名用LeetCode題目編號表示
- Solution.java ——算法類,注意到LeetCode每道題目的代碼類名爲Solution
- main.java ——包含主函數(控制邏輯、測試用例數組)、測試函數(測試結果輸出、算法耗時)
- pid2
- Solution.java
- main.java
- pid1 ——題目包,每一個題目封裝在一個單獨的包中,包名用LeetCode題目編號表示
以具體題目爲例:96. Unique Binary Search Trees數組
- 拿到題目,首先在Eclipse中創建題目包pid96;
- 新建類:main.java,並建立方法: main 和 test;
- 新建類:Solution.java,將算法方法代碼用題目中原始代碼進行替換,並添加默認返回值;
- 在main方法中新建測試用例數組,並循環調用測試模塊test(ito);
- 在test方法中實例化Solution類,添加計時語句,並在計時語句內部加入執行算法語句。
至此,答題框架搭建完畢,代碼內容以下:框架
main.java
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
30
31
32
33
34
35
36
37
38
39
|
package pid96;
/**
* Unique Binary Search Trees
*
* Given n, how many structurally unique BST's
* (binary search trees) that store values 1...n?
*
* For example, Given n = 3, there are a total of 5 unique BST's.
*
* 1 3 3 2 1
* \ / / / \ \
* 3 2 1 1 3 2
* / / \ \
* 2 1 2 3
*
*
@author 白
*
*/
public class main {
public static void main(String[] args) {
int[] testTable = { 0, 1, 2, 3, 4, 5, 6, 10, };
for (int ito : testTable) {
test(ito);
}
}
private static void test(int ito) {
Solution solution =
new Solution();
int rtn;
long begin = System.currentTimeMillis();
rtn = solution.numTrees(ito);
long end = System.currentTimeMillis();
System.out.println(ito +
": rtn=" + rtn);
System.out.println();
System.out.println(
"耗時:" + (end - begin) + "ms");
System.out.println(
"-------------------");
}
}
|
Solution.java
1
2
3
4
5
6
7
|
package pid96;
public class Solution {
public int numTrees(int n) {
return 0;
}
}
|
接下來開始寫算法,所有在Solution.java中完成。函數
完成後以下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package pid96;
public class Solution {
public int numTrees(int n) {
if(n<=1)return 1;
if(n==2)return 2;
int [] table= new int [n+1];
table[
0]=1;
table[
1]=1;
table[
2]=2;
for(int i=2;i<n;i++)
for(int j=0;j<=i;j++)
table[i+
1]+=table[i-j]*table[j];
return table[n];
}
}
|
運行結果:post
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
30
31
32
|
0: rtn=1
耗時:0ms
-------------------
1: rtn=1
耗時:0ms
-------------------
2: rtn=2
耗時:0ms
-------------------
3: rtn=5
耗時:0ms
-------------------
4: rtn=14
耗時:0ms
-------------------
5: rtn=42
耗時:0ms
-------------------
6: rtn=132
耗時:0ms
-------------------
10: rtn=16796
耗時:0ms
-------------------
|