Pascal's 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] ]
没什么特别的, 就是一层一层的做就行了。 时间复杂度是O(n2)。
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> generate(int numRows) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 6 if(numRows == 0) 7 return result; 8 ArrayList<Integer> pre = new ArrayList<Integer>(); 9 pre.add(1); 10 result.add(pre); 11 if(numRows == 1) 12 return result; 13 pre = new ArrayList<Integer>(); 14 pre.add(1); 15 pre.add(1); 16 result.add(pre); 17 if(numRows == 2) 18 return result; 19 for(int i = 3; i < numRows + 1; i ++){ 20 ArrayList<Integer> item = new ArrayList<Integer>(); 21 item.add(1); 22 for(int j = 0; j < pre.size() - 1; j ++){ 23 item.add(pre.get(j) + pre.get(j + 1)); 24 } 25 item.add(1); 26 pre = item; 27 result.add(item); 28 } 29 return result; 30 } 31 }
第二遍:
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> generate(int numRows) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 6 if(numRows < 1) return result; 7 ArrayList<Integer> row = new ArrayList<Integer>(); 8 row.add(1); 9 result.add(row); 10 if(numRows == 1) return result; 11 for(int i = 1; i < numRows; i ++){ 12 ArrayList<Integer> tmp = new ArrayList<Integer>(); 13 tmp.add(1); 14 ArrayList<Integer> pre = result.get(i - 1); 15 for(int j = 0; j < pre.size() - 1; j ++){ 16 tmp.add(pre.get(j) + pre.get(j + 1)); 17 } 18 tmp.add(1); 19 result.add(tmp); 20 } 21 return result; 22 } 23 }
posted on 2013-04-18 09:00 Step-BY-Step 阅读(197) 评论(0) 编辑 收藏 举报