LeetCode: Pascal's Triangle 解题报告

Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

SOLUTION 1:
很easy的题。注意记得把List加到ret中。
比较简单,每一行的每一个元素有这个规律:
1. 左右2边的是1.
i, j 表示行,列坐标。
2. 中间的是f[i][j] = f[i - 1][j] + f[i - 1][j - 1]
不断复用上一行的值即可。
 1 public class Solution {
 2     public List<List<Integer>> generate(int numRows) {
 3         List<List<Integer>> ret = new ArrayList<List<Integer>>();
 4         
 5         for (int i = 0; i < numRows; i++) {
 6             List<Integer> list = new ArrayList<Integer>();
 7             for (int j = 0; j <= i; j++) {
 8                 if (j == 0 || i == j) {
 9                     list.add(1);
10                 } else {
11                     int sum = ret.get(i - 1).get(j - 1) + ret.get(i - 1).get(j);
12                     list.add(sum);
13                 }
14             }
15             
16             // BUG 1: forget this statement.
17             ret.add(list);
18         }
19         
20         return ret;        
21     }
22 }
View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/list/Generate.java

posted on 2014-12-30 23:44  Yu's Garden  阅读(623)  评论(0编辑  收藏  举报

导航