码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Pascal's Triangle 解题报告

时间:2014-12-31 00:51:58      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

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

LeetCode: Pascal's Triangle 解题报告

标签:

原文地址:http://www.cnblogs.com/yuzhangcmu/p/4194821.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!