题目描述 :pascals-triangle
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] ]
代码如下:
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> generate(int numRows) {
ArrayList<ArrayList<Integer>> tri=new ArrayList();
if(numRows == 0)
return tri;
ArrayList<Integer> first=new ArrayList();
first.add(1);
tri.add(first);
if(numRows == 1)
{
return tri;
}
first=new ArrayList();
first.add(1);
first.add(1);
tri.add(first);
if(numRows == 2)
{
return tri;
}
for(int row=3;row<=numRows;row++)
{
ArrayList<Integer> second=new ArrayList();
second.add(1);
for(int i=0;i<first.size()-1;i++)
{
int temp=first.get(i)+first.get(i+1);
second.add(temp);
}
second.add(1);
tri.add(second);
first=second;
}
return tri;
}
}
题目描述:pascals-triangle-ii
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return[1,3,3,1]. 即row的下标从0开始。
Note:
Could you optimize your algorithm to use only O(k) extra space?
import java.util.*;
public class Solution {
public ArrayList<Integer> getRow(int rowIndex) {
ArrayList<Integer> first=new ArrayList();
first.add(1);
if(rowIndex == 0)
{
return first;
}
first.add(1);
if(rowIndex == 1)
{
return first;
}
for(int row=2;row<=rowIndex;row++)
{
ArrayList<Integer> second=new ArrayList();
second.add(1);
for(int i=0;i<first.size()-1;i++)
{
int temp=first.get(i)+first.get(i+1);
second.add(temp);
}
second.add(1);
first=second;
}
return first;
}
}