Advertisement
epsilon413

pascals triangle

Jun 26th, 2024
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | Source Code | 0 0
  1. /*
  2. I can use two pointers to make this happen,
  3.  
  4. The ith entry of the row contains 'i' elements
  5.  
  6. the first and last entries of the list is '1'
  7.  
  8. 1 -> 1
  9. 2 -> 2
  10. 3 -> 3
  11. 4 -> 4
  12.  
  13. */
  14.  
  15. class Solution {
  16. public:
  17.     vector<vector<int>> generate(int numRows) {
  18.         // Create the triangle
  19.         vector<vector<int>> pascal;
  20.  
  21.         // Iterate over the triangle to fill it
  22.         for(int k = 0; k < numRows; k++) {
  23.             // Create a new row, with first and last entry as 1
  24.             vector<int> row = vector<int>(k+1, 1);
  25.  
  26.             // push the row
  27.             pascal.emplace_back(row);
  28.  
  29.             // If length is greater than 2
  30.             if(k >= 2) {
  31.                 // Use two pointers to fill the array,
  32.                 // left will start for the 0th index, right will go upto the last index
  33.                 int l = 0, r = 1;
  34.                 while(r != k) {
  35.                     pascal[k][l+1] = pascal[k-1][l] + pascal[k-1][r];
  36.                     l++;
  37.                     r++;
  38.                 }
  39.             }
  40.         }
  41.         return pascal;
  42.     }
  43. };
Tags: leetcode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement