Question:
//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]
//]
Answer:
package LeetCode;
import java.util.*;
public class pascalTriangle {
//failed method
// public static int[][] pascalTriangle(int rows){
// int[][] pascal = new int[rows][];
//
// for(int i =0;i<pascal.length;i++){
// pascal[i] = new int [i+1];
// pascal[i][0] = 1;
// pascal[i][pascal[i].length-1] = 1;
// for(int j=1;j<i+1;j++){
// pascal[i][j] = pascal[i-1][j-1]+pascal[i-1][j];
// }
// }
// return pascal;
// }
// method prints successfully
// public static void triangle (int rows){
// int[][] pascal = new int[rows][];
//
// for(int i =0;i<pascal.length;i++){
// pascal[i] = new int [i+1];
//
// for(int j=0;j<i+1;j++){
// if(i==0||j==0|j==i){
// pascal[i][j]=1;
// }else{
// pascal[i][j] = pascal[i-1][j-1]+pascal[i-1][j];
// }
// System.out.print(pascal[i][j]+" ");
// }
// System.out.println();
// }
// }
public static List<List<Integer>> triangle(int rows){
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (rows<=0) return result;
List<Integer> pre= new ArrayList<Integer>();
pre.add(1);
result.add(pre);
for (int i=2;i<=rows;i++){
List<Integer> cursor = new ArrayList<Integer>();
cursor.add(1);
for(int j=0;j<pre.size()-1;j++){
cursor.add(pre.get(j)+pre.get(j+1));
}
cursor.add(1);
pre = cursor;
result.add(cursor);
}
return result;
}
public static void main(String[] args){
int n=5;
System.out.println(triangle(n));
}
}
Result
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
网友评论