« Back
read.

LeetCode 119 Pascal's Triangle II.

LeetCode 119 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?

Not a hard question, but if you do not know ArrayList.add and ArrayList.set, then you may get into trouble(that's what I meet).


public class Solution {
    public List getRow(int rowIndex) {
       List result=new ArrayList(); 
       if(rowIndex < 0){
           return result;
       }
       for(int i=0;i < rowIndex+1;i++){
          result.add(0,1);
          for(int k=1;k < result.size()-1;k++){

              result.set(k,result.get(k)+result.get(k+1));
          }
       }
       return result;
    }
}
comments powered by Disqus