24. Pascal Triangle
My Approach
Explain with Example
Time and Auxiliary Space Complexity
Code (C++)
Contribution and Support
Last updated
Last updated
- Initialization: out = [1, 1, 1, 1, 1], prev = [1, 1, 1, 1, 1]
- After the first iteration, out = [1, 2, 1, 1, 1], prev = [1, 1, 1, 1, 1]
- After the second iteration, out = [1, 3, 3, 1, 1], prev = [1, 2, 1, 1, 1]
- After the third iteration, out = [1, 4, 6, 4, 1], prev = [1, 3, 3, 1, 1] which is the 5th row of Pascal Triangle.class Solution {
public:
int mod = 1e9 + 7;
vector<long long> nthRowOfPascalTriangle(int n) {
vector<long long> out(n, 1), prev(n, 1);
for (int i = 1; i < n; ++i) {
for (int j = 1; j < i; ++j) {
out[j] = (prev[j] + prev[j - 1]) % mod;
}
prev = out;
}
return out;
}
};