一、题目叙述:
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] ]
Subscribe to see which companies asked this question
二、解题思路:
非常简单的题,只用知道杨辉三角的定义及规律即可。。。
三、源码:
import java.util.ArrayList;
import java.util.List;
public class Solution
{
public List<List<Integer>> generate(int numRows)
{
List<List<Integer>> result = new ArrayList<List<Integer>>();
for (int i = 0; i < numRows; i++)
{
List<Integer> a = new ArrayList<Integer>();
//if (i == 0) {return result;}
if (i == 0) {a.add(1); result.add(a);}
else
{
a.add(1);
for (int j = 1; j < i; j++)
{
a.add(result.get(i - 1).get(j - 1) + result.get(i - 1).get(j));
}
a.add(1);
result.add(a);
}
}
return result;
}
public static void main(String args[])
{
int target = 5;
Solution solution = new Solution();
System.out.println(solution.generate(target));
}
}