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?
Original algorithm (recursive approach) can be referred to .
Idea of using only O(k) extra space is reusing the same array list to form the current row of numbers. Iterations will be from 0th row ([1]) to kth row. And for each iteration, we need to form the current base on the previous row.
For example, in 3th row, we have [1,3,3,1]. So in the iteration of 4th row, we need only add 1 at the beginning of this array list, overwritten the 2nd element to 1+3=4, 3rd element to 3+3=6, 4th element to 3+1=4, and keep the last element remain unchanged. Then we would have all the numbers of 4th row, i.e.[1,4,6,4,1].
1 public class Solution { 2 public ListgetRow(int rowIndex) { 3 ArrayList res = new ArrayList (); 4 if (rowIndex < 0) return res; 5 for (int i=0; i<=rowIndex; i++) { 6 for (int j=i; j>=0; j--) { 7 if (j == i) res.add(1); 8 else if (j > 0) { 9 res.set(j, res.get(j-1)+res.get(j));10 }11 }12 }13 return res;14 }15 }
1 public class Solution { 2 public ArrayListgetRow(int rowIndex) { 3 ArrayList list = new ArrayList (); 4 list.add(1); 5 int prev, current; 6 for (int i = 0; i <= rowIndex; i++) { 7 prev = 1; 8 for (int j = 0; j <= i; j++) { 9 if (j == 0) continue;10 if (j == i) list.add(1);11 else {12 current = list.get(j);13 list.set(j, current + prev);14 prev = current;15 }16 }17 }18 return list;19 }20 }
1 public ArrayListgetRow(int rowIndex) { 2 ArrayList res = new ArrayList (); 3 if(rowIndex<0) 4 return res; 5 res.add(1); 6 for(int i=1;i<=rowIndex;i++) 7 { 8 for(int j=res.size()-2;j>=0;j--) 9 {10 res.set(j+1,res.get(j)+res.get(j+1));11 }12 res.add(1);13 }14 return res;15 }