🎉 One-stop destination for all your technical interview Preparation 🎉
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown
rowIndex==0
(first row) then we only have {1}
in the row.1
always.currentRow[i]
by adding previousRow[i]
and previousRow[i+1]
.if(rowIndex==0) return {1};
currentRow[i] = (previousRow[i-1]+previousRow[i]);
Before reading out please give it a try now.
currentRow[0] = 1
previousRow = getRow(rowIndex-1);
currentRow[i] = (previousRow[i-1]+previousRow[i]);
currentRow
.class Solution {
public:
vector<int> getRow(int rowIndex) {
if(rowIndex==0) return {1}; // Base Case
vector<int> currentRow = {1}; // current row with 1 value in it
vector<int> previousRow = getRow(rowIndex-1); // get the previous row
// Now fill the current row based on previous row
for(int i=1;i<rowIndex;i++){
currentRow.push_back(previousRow[i-1]+previousRow[i]);
}
currentRow.push_back(1); // fill the last element of current row
return currentRow;
}
};