LeetCode --- 118 杨辉三角Ⅰ

2020-02-04  本文已影响0人  KM_0d16

LeetCode --- 字符串、数组
简书专栏:https://www.jianshu.com/nb/41796568
知乎专栏:https://zhuanlan.zhihu.com/c_174823416

一、题目描述

来源:力扣(LeetCode)
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:
输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
要求实现函数:
public List<List<Integer>> generate(int numRows) {}

二、实现思路以及代码

可以根据题意得知,每一行都是由前一行依次相加得到的,且每一行的首尾都是由1构成,所以要得到当前行,只需要遍历上一行,依次相加即可得到中间部分的值,两端是1。从代码中理解更为容易。

public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<>();
        if (numRows <= 0) {
            return result;
        }
        result.add(new ArrayList<>());
        result.get(0).add(1);
        for (int i = 2; i <= numRows; i++) {
            ArrayList<Integer> aList = new ArrayList<>();
            //首字母为1
            aList.add(1);


            //添加中间元素
            for(int j = 1; j < i - 1; j++) {
                //i-2是因为第i行的数由第i-1行确定,存放在List中的i-2位置
                aList.add(result.get(i - 2).get(j - 1) + result.get(i - 2).get(j));
            }

            //添加末尾元素
            aList.add(1);
            result.add(aList);
        }
        return result;           
    }

三、测试代码

public static void main(String[] args) {
        List<List<Integer>> list = generate(6);
        for (List<Integer> te : list) {
            for(int cur : te) {
                System.out.print(cur + " ");
            }
            System.out.println();
        }
    }

输出结果为:

1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1 
上一篇下一篇

猜你喜欢

热点阅读