
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pascal's Triangle II in C++
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 −
#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, ]
Advertisements