0
点赞
收藏
分享

微信扫一扫

LeetCode Top Interview Questions 118. Pascal's Triangle (Java版; Easy)


​​welcome to my blog​​

LeetCode Top Interview Questions 118. Pascal’s Triangle (Java版; Easy)

题目描述

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

LeetCode Top Interview Questions 118. Pascal

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

第一次做; 完全复现杨辉三角形的计算过程; 索引还是从0开始吧, 别从1开始, 细心点; 推荐下面的动态规划解法

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


class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
if(numRows<1)
return res;
List<Integer> tmp;
//
for(int i=0; i<numRows; i++){
tmp = new ArrayList<>();
for(int j=0; j<=i; j++){
if(j==0 || j==i)
tmp.add(1);
else{
tmp.add(j, res.get(i-1).get(j-1)+res.get(i-1).get(j));
}
}
res.add(new ArrayList<Integer>(tmp));
}
return res;
}
}

第一次做; 按照下面LeetCode动态规划解的思想写了一遍; 我最开始思考这道题的时候, 比较难下手的原因是因为计算当前行的值需要上一行的值, 如何获取上一行的值? 这里直接把上一行的结果经过简单的处理, 就是在index=0处加入1, 然后根据这个简单处理后的结果计算新一行的结果; 接着再简单处理新一行的结果, 以此类推; 非常巧妙! 看下面的力扣图, 之所以要add(0,1),是因为每一行的第一个数都是1, 并且每一行的第二个数的一个加数一定是1, 所以加入一个1让其作为新的开头, 第二个1用来计算

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


class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
if(numRows<1)
return res;
List<Integer> tmp = new ArrayList<>();
//
for(int i=0; i<numRows; i++){
tmp.add(0,1);
for(int j=1; j<=tmp.size()-2; j++){
tmp.set(j, tmp.get(j)+tmp.get(j+1));
}
res.add(new ArrayList<Integer>(tmp));
}
return res;
}
}

​​力扣图​​

LeetCode Top Interview Questions 118. Pascal

​​LeetCode优秀题解​​; 动态规划, 看上面的图,想清楚为什么要add(0,1), 这跟杨辉三角形的计算过程有关

计算过程:
1
1 1
1 1 1 → 1 2 1
1 1 2 1 → 1 3 3 1
1 1 3 3 1 → 1 4 6 4 1

public class Solution {
public List<List<Integer>> generate(int numRows){
List<List<Integer>> allrows = new ArrayList<List<Integer>>();
ArrayList<Integer> row = new ArrayList<Integer>();
for(int i=0;i<numRows;i++)
{
row.add(0, 1);
for(int j=1;j<row.size()-1;j++)
row.set(j, row.get(j)+row.get(j+1));
allrows.add(new ArrayList<Integer>(row));
}
return allrows;

}
}

​​LeetCode优秀题解​​; 直接还原了杨辉三角的计算过程

class Solution {
public List<List<Integer>> generate(int numRows) {

List<List<Integer>> result = new ArrayList<>();

for(int i = 0 ; i < numRows; i++) {
List<Integer> list = new ArrayList<>();

for(int j = 0; j < i + 1 ; j++) {
if(j == 0 || j == i) {
list.add(1);
}
else {
int a = result.get(i - 1).get(j - 1);
int b = result.get(i - 1).get(j);
list.add(a + b);
}
}
result.add(list);
}
return result;
}
}


举报

相关推荐

0 条评论