
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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, ]
- Related Articles
- Triangle in C++
- Sum of upper triangle and lower triangle in C++
- Valid Triangle Number in C++
- Permutations II in C++
- Subsets II in C++
- Pascal's Triangle in C++
- Combination Sum II in C++
- Unique Paths II in C++
- House Robber II in C++
- Smallest Range II in C++
- Stone Game II in C++
- Majority Element II in C++
- Ugly Number II in C++
- H-Index II in C++
- Range Addition II in C++

Advertisements