# LeetCode算法题-Pascal's Triangle II（Java实现）

### 02 第一种解法

public List<Integer> getRow(int rowIndex) {
List<Integer> list = new ArrayList<Integer>();
for (int k = 0; k <= rowIndex; k++) {
}
for (int i = 1; i < rowIndex; i++) {
for (int j = i; j > 0; j--) {
list.set(j, list.get(j - 1) + list.get(j));
}
}
return list;
}

### 03 第二种解法

public List<Integer> getRow2(int rowIndex) {
List<Integer> list = new ArrayList<>();
for (int r = 0; r <= rowIndex; r++) {
for (int i = 1; i < r; i++) {
list.set(i, list.get(i) + list.get(i + 1));
}
}
return list;
}

### 04 第三种解法

public List<Integer> getRow3(int rowIndex) {
List<Integer> list = new ArrayList<Integer>();
int[] result = new int[1];
for (int i = 0; i <= rowIndex; i++) {
int[] next = new int[i + 1];
next[0] = 1;
next[i] = 1;
for (int j = 1; j < i; j++) {
next[j] = result[j - 1] + result[j];
}
result = next;
}
for (int in : result) {
}
return list;
}

### 05 验证与测试

public static void main(String[] args) {
Easy_119_PascalTriangleII instance = new Easy_119_PascalTriangleII();
int rowIndex = 3;
long start = System.nanoTime();
List<Integer> list = instance.getRow(rowIndex);
long end = System.nanoTime();
System.out.println("getRow---输入："+rowIndex+" , 输出："+list+" , 用时："+(end-start)/1000+"微秒");
long start2 = System.nanoTime();
List<Integer> list2 = instance.getRow2(rowIndex);
long end2 = System.nanoTime();
System.out.println("getRow2---输入："+rowIndex+" , 输出："+list2+" , 用时："+(end2-start2)/1000+"微秒");
long start3 = System.nanoTime();
List<Integer> list3 = instance.getRow3(rowIndex);
long end3 = System.nanoTime();
System.out.println("getRow3---输入："+rowIndex+" , 输出："+list3+" , 用时："+(end3-start3)/1000+"微秒");
}

getRow---输入：10 , 输出：[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1] , 用时：73微秒
getRow2---输入：10 , 输出：[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1] , 用时：48微秒
getRow3---输入：10 , 输出：[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1] , 用时：24微秒

### 06 小结

posted @ 2018-11-14 08:11  程序员小川  阅读(...)  评论(...编辑  收藏