Pascal's Triangle (Java)
2014-12-23 17:05
260 查看
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Source
Test
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Source
public static List<List<Integer>> generate(int numRows){ List<List<Integer>> s = new ArrayList<List<Integer>>(); if(numRows == 0) return s; ArrayList<Integer> a = new ArrayList<Integer>(); a.add(1); s.add(a); //注意二维的赋值问题 不能直接添加1 for(int i = 1; i < numRows; i++){ List<Integer> t = new ArrayList<Integer>(); t.add(1); for(int j = 1; j <= i - 1 ; j++){ t.add(s.get(i - 1).get(j - 1) + s.get(i - 1).get(j)); } t.add(1); s.add(t); } return s; }
Test
public static void main(String[] args){ System.out.println(generate(5)); }
相关文章推荐
- Pascal's Triangle Java
- Pascal's Triangle II (Java)
- [Leetcode] Pascal's Triangle (Java)
- [LeetCode][119. Pascal's Triangle II][easy]Java实现,杨辉三角
- 【LeetCode-面试算法经典-Java实现】【118-Pascal's Triangle(帕斯卡三角形)】
- 【leetcode】Pascal's Triangle II(Java)
- leetcode:Pascal's Triangle 【Java】
- 基于Java实现杨辉三角 LeetCode Pascal's Triangle
- [3]118. Pascal's Triangle(Java)
- leetcode: Pascal's Triangle | Java最短代码实现
- 【leetcode】Pascal's Triangle[java]
- LeetCode|Pascal's Triangle-java
- Leetcode:118. Pascal's Triangle(JAVA)
- 【leetcode】119. Pascal's Triangle II【java】
- 【LeetCode-面试算法经典-Java实现】【118-Pascal's Triangle(帕斯卡三角形)】
- Leetcode:119. Pascal's Triangle II(JAVA)
- Pascal's Triangle (java)
- LeetCode(118) Pascal's Triangle (Java)
- 【leetcode】118. Pascal's Triangle【java】
- leetcode:Pascal's Triangle II 【Java】