前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode118 Pascal's Triangle

leetcode118 Pascal's Triangle

作者头像
用户1665735
发布2018-06-20 16:15:58
3970
发布2018-06-20 16:15:58
举报
文章被收录于专栏:kevindroidkevindroid

题目

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

For example, given numRows = 5, Return

代码语言:javascript
复制
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

生成给定行数的帕斯卡三角形。

解题思路

利用帕斯卡三角形的性质即可很简单的解决。 性质:第n行的第1个数为1,第二个数为1×(n-1),第三个数为1×(n-1)×(n-2)/2,第四个数为1×(n-1)×(n-2)/2×(n-3)/3…依此类推。

代码语言:javascript
复制
public class leetcode118 {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<>();
        for (int n = 1; n <= numRows; n++) {
            List<Integer> temp = new ArrayList<>();
            int num = 1;
            for (int k = 1; k <= n; k++) {
                if (k == 1)
                    num = 1;
                else
                    num = num * (n - k+1) / (k - 1);
                temp.add(num);
            }
            res.add(temp);
        }
        return res;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年05月05日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 解题思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档