runnig

[leetcode] 119 Pascal Triangle 2 c++

Feb 3rd, 2013
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. // http://leetcode.com/onlinejudge#question_119
  2. /*
  3. Given an index k, return the kth row of the Pascal's triangle.
  4.  
  5. For example, given k = 3,
  6. Return [1,3,3,1].
  7.  
  8. Note:
  9. Could you optimize your algorithm to use only O(k) extra space?
  10.  
  11. */
  12. class Solution {
  13. public:
  14.     vector<int> getRow(const int rowIndex) {
  15.         typedef std::vector<int> row_t;
  16.         typedef std::vector<row_t> tri_t;
  17.        
  18.         row_t prev(rowIndex+1,1), curr(rowIndex+1,1);
  19.                
  20.         for(int row_no = 0; row_no < rowIndex+1; ++row_no)
  21.         {
  22.             std::swap(prev,curr);
  23.            
  24.             curr[0] = curr[row_no] = 1;
  25.             for(int j = 1; j < row_no; ++j)
  26.             {
  27.                 curr[j] = prev[j-1] + prev[j];
  28.             }
  29.            
  30.         }
  31.        
  32.        
  33.         return curr;
  34.        
  35.     }
  36. };
Advertisement
Add Comment
Please, Sign In to add comment