118. Pascal's Triangle
原题链接:https://leetcode.com/problems/pascals-triangle/description/
哈哈哈哈,又见到了大名鼎鼎的杨辉三角。这道题目级别是容易,初看较难,再看还是简单:
import java.util.ArrayList;
import java.util.List;
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.generate(0));
System.out.println(s.generate(1));
System.out.println(s.generate(5));
System.out.println(s.generate(6));
}
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>(numRows);
if (numRows < 1) {
return res;
}
List<Integer> pre = new ArrayList<>(1);
pre.add(1);
res.add(pre);
for (int i = 2; i <= numRows; i++) {
List<Integer> current = new ArrayList<>(i);
for (int j = 0; j < i; j++) {
if ((j - 1) >= 0 && j < pre.size()) {
current.add(pre.get(j - 1) + pre.get(j));
}
if ((j - 1) >= 0 && j >= pre.size()) {
current.add(pre.get(j - 1));
}
if ((j - 1) < 0 && j < pre.size()) {
current.add(pre.get(j));
}
}
res.add(current);
pre = current;
}
return res;
}
}
反正我就是使用了最简单最直接的方法实现了,不过官方解答里说的也是这种方法了,而且还称它为动态规划!