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?

  

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
       vector<int> result(rowIndex+1);
       result[0] = 1;
      
        int temp1 = 0, temp2 = 0;
        for(int i = 1; i<= rowIndex ; i++)
          for(int j = 0; j< i+1; j++){
            temp2 = result[j]; 
            if(j == 0 || j == i)
                result[j] = 1;
             else 
                 result[j] += temp1 ;    
            temp1 = temp2;  
          }
          
          return result;
    }
};

 

posted @ 2013-08-11 16:53  冰点猎手  阅读(171)  评论(0编辑  收藏  举报