LeetCode包括main函数的答题框架(Java+Eclipse)

http://zhangnai.xin/2016/09/20/LeetCode-Framework/

目录结构:

  • LeetCode ——项目名称,方便Eclipse内置Git对代码进行管理和多终端同步
    • pid1 ——题目包,每个题目封装在一个单独的包中,包名用LeetCode题目编号表示
      • Solution.java ——算法类,注意到LeetCode每道题目的代码类名为Solution
      • main.java ——包含主函数(控制逻辑、测试用例数组)、测试函数(测试结果输出、算法耗时)
    • pid2 
      • Solution.java
      • main.java  

以具体题目为例:96. Unique Binary Search Trees

  1. 拿到题目,首先在Eclipse中建立题目包pid96;
  2. 新建类:main.java,并创建方法: main 和 test;
  3. 新建类:Solution.java,将算法方法代码用题目中原始代码进行替换,并添加默认返回值;
  4. 在main方法中新建测试用例数组,并循环调用测试模块test(ito);
  5. 在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];
}
}

运行结果:

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
-------------------

 

 
 
posted @ 2017-12-09 16:31  苗妙苗  阅读(5776)  评论(1编辑  收藏  举报