LeetCode0118-杨辉三角

LeetCode0118-杨辉三角

题目:

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
LeetCode0118-杨辉三角_第1张图片

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

代码:

import java.util.ArrayList;
import java.util.List;

/**
 * 0118-杨辉三角
 * 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
 * 

* 在杨辉三角中,每个数是它左上方和右上方的数的和。 *

* 示例: *

* 输入: 5 * 输出: * [ * [1], * [1,1], * [1,2,1], * [1,3,3,1], * [1,4,6,4,1] * ] */ class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> result = new ArrayList<>(); for (int i = 0; i < numRows; i++) { List<Integer> row = new ArrayList<>(); for (int j = 0; j <= i; j++) { if (j == 0 || j == i) { row.add(1); } else { row.add(result.get(i - 1).get(j - 1) + result.get(i - 1).get(j)); } } result.add(row); } return result; } } /** * 测试 */ public class Study0118 { public static void main(String[] args) { List<List<Integer>> result = new Solution().generate(5); System.out.println(result); } }

结果:

LeetCode0118-杨辉三角_第2张图片

你可能感兴趣的:(LeetCode,leetcode,java,杨辉三角)