# Pascal's Triangle II in C++

C++Server Side ProgrammingProgramming

Suppose we have a non-negative index k where k ≤ 33, we have to find the kth index row of Pascal's triangle.

So, if the input is like 3, then the output will be [1,3,3,1]

To solve this, we will follow these steps −

• Define an array pascal of size rowIndex + 1 and fill this with 0

• for initialize r := 0, when r <= rowIndex, update (increase r by 1), do −

• pascal[r] := 1, prev := 1

• for initialize i := 1, when i < r, update (increase i by 1), do −

• cur := pascal[i]

• pascal[i] := pascal[i] + prev

• prev := cur

• return pascal

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> pascal(rowIndex + 1, 0);
int prev, cur, r, i;
for (r = 0; r <= rowIndex; r++) {
pascal[r] = prev = 1;
for (i = 1; i < r; i++) {
cur = pascal[i];
pascal[i] += prev;
prev = cur;
}
}
return pascal;
}
};
main(){
Solution ob;
print_vector(ob.getRow(3));
}

## Input

3

## Output

[1, 3, 3, 1, ]