118. Pascal's Triangle java solutions

For example, given numRows = 5,
Return

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

Subscribe to see which companies asked this question

 1 public class Solution {
 2     public List<List<Integer>> generate(int numRows) {
 3         List<List<Integer>> ans = new ArrayList<List<Integer>>();
 4         if(numRows < 1) return ans;
 5         int r = 0;
 6         while(r < numRows){
 7             List<Integer> tmp = new ArrayList<Integer>(r+1);
 8             if(r == 0){
 9                 tmp.add(1);
10             }else{
11                 int c = 0;
12                 while(c < r+1){
13                     if(c == 0 || c == r) tmp.add(1);
14                     else{
15                         tmp.add(ans.get(r-1).get(c)+ans.get(r-1).get(c-1));
16                     }
17                     c++;
18                 }
19             }
20             ans.add(tmp);
21             r++;
22         }
23         return ans;
24     }
25 }

根据杨辉三角的数学定义来做。

解法2:

参照Pascal's Triangle 2 的解法。

119. Pascal's Triangle II java solutions

posted @ 2016-07-06 11:06  Miller1991  阅读(159)  评论(0编辑  收藏  举报