118. Pascal's Triangle
程序员文章站
2022-04-01 11:31:47
...
Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
题解:
package com.leetcode;
import java.util.*;
public class PascalTriangle {
public static void main(String[] args) {
List<List<Integer>> ans = generate(5);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans.get(i).size(); j++)
System.out.print(ans.get(i).get(j) + " ");
System.out.println();
}
}
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
for (int i = 1; i <= numRows; i++) {
if (i == 1) {
List<Integer> currRow = new ArrayList<Integer>();
currRow.add(1);
ans.add(currRow);
} else if (i == 2) {
List<Integer> currRow = new ArrayList<Integer>();
currRow.add(1);
currRow.add(1);
ans.add(currRow);
} else {
List<Integer> currRow = new ArrayList<Integer>();
List<Integer> prevRow = ans.get(i - 2);
for (int j = 0; j < prevRow.size(); j++) {
if (j == 0)
currRow.add(1);
else
currRow.add(prevRow.get(j) + prevRow.get(j - 1));
}
currRow.add(1);
ans.add(currRow);
}
}
return ans;
}
}
推荐阅读
-
POJ 2704 Pascal's Travels G++ dfs记忆化搜索
-
Leetcode No.119 Pascal's Triangle II(c++实现)
-
杨辉三角(pascal's triangle)
-
LeetCode-119. Pascal's Triangle II
-
119. Pascal's Triangle II [杨辉三角形2]
-
119. Pascal's Triangle II
-
leetcode -- 119. Pascal's Triangle II
-
2018.05.03 leetcode #119. Pascal's Triangle II
-
【leetcode】119. Pascal's Triangle II
-
LeetCode 119. Pascal's Triangle II