LeetCode | Pascal's 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]
.
Note: Could you optimize your algorithm to use only O(k) extra space?
按昨天的思路,不考虑空间复杂度的优化:
//当index=3时,numRows=4 //额外使用了3个list,题目建议只用一个,运行可以accept public class Solution { public List<Integer> getRow(int rowIndex) { List<Integer> result = new ArrayList<Integer>(); List<Integer> preRow = new ArrayList<Integer>(); preRow.add(0); for(int i=1; i<=rowIndex+1; i++){ List<Integer> curRow = new ArrayList<Integer>(); for(int j=0; j<i; j++){ if(j < 1){ curRow.add(1); }else if(j >= preRow.size()){ curRow.add(1); }else{ curRow.add(preRow.get(j-1) + preRow.get(j)); } } preRow = curRow; result = curRow; } return result; } }
优化空间复杂度,只适用一个list:
//优化空间复杂度:直接在preRow的list上覆写生成curRow,来节省空间 //思路:row.set(index, Integer) => row.set(j, row.get(j-1)+row.get(j)) //但是这样的正向遍历是有问题的,本次row.set(j, row[j-1] + row[j]),则下次计算时 //row.set(j+1, row[j] + row[j+1]),虽然row[j+1]还是preRow中的值,但是row[j]已经被覆写了, //而不是preRow的值了,再相加时就不符合杨辉三角了。因而要反向遍历,避免数据污染 public class Solution { public List<Integer> getRow(int rowIndex) { List<Integer> row = new ArrayList<Integer>(); row.add(1); //rowIndex<=0时,跳过循环到return,因而不需额外判断 for(int i=1; i<=rowIndex; i++){ //i表示index,第1行的index为0 for(int j=row.size()-1; j>0; j--){ //反向遍历填充第i行的[1~~length-1] row.set(j, row.get(j-1)+row.get(j)); //row[0]恒为1,不能覆盖 } row.add(1); //在末尾add一个1,构成新row } return row; } }