patterncppMajor
Solution for kth row of Pascal's triangle for a job interview
Viewed 0 times
pascaljobtriangleinterviewforkthsolutionrow
Problem
Question:
Given an index \$k\$, return the \$k^{th}\$ row of the Pascal's triangle.
For example, given \$k = 3\$, return \$[1,3,3,1]\$. Bonus points for using \$O(k)\$ space.
Can it be further optimized using this way or another?
Given an index \$k\$, return the \$k^{th}\$ row of the Pascal's triangle.
For example, given \$k = 3\$, return \$[1,3,3,1]\$. Bonus points for using \$O(k)\$ space.
Can it be further optimized using this way or another?
class Solution {
public:
long long C(int n, int r) {
if(r > n / 2) r = n - r; // because C(n, r) == C(n, n - r)
long long ans = 1;
int i;
for(i = 1; i getRow(int rowIndex) {
vector v;
long long sol;
for(int i=0;i<=rowIndex;i++)
{sol=C(rowIndex,i);
v.push_back(sol);}
return v;
}
};Solution
For one thing, the inconsistency with whitespace use and curly brace placing may demonstrate a lack of attention to detail. Before you attack the actual problem, make sure your code is written cleanly.
This:
should use some whitespace:
You already do this in other places, and it should be done everywhere.
Also, this:
looks a bit sloppy and is harder to read. Again, use more whitespace, but also separate the loop body from the curly braces.
This:
for(int i=0;i<=rowIndex;i++)should use some whitespace:
for (int i = 0; i <= rowIndex; i++)You already do this in other places, and it should be done everywhere.
Also, this:
for(int i=0;i<=rowIndex;i++)
{sol=C(rowIndex,i);
v.push_back(sol);}looks a bit sloppy and is harder to read. Again, use more whitespace, but also separate the loop body from the curly braces.
for (int i = 0; i <= rowIndex; i++) {
sol = C(rowIndex, i);
v.push_back(sol);
}Code Snippets
for(int i=0;i<=rowIndex;i++)for (int i = 0; i <= rowIndex; i++)for(int i=0;i<=rowIndex;i++)
{sol=C(rowIndex,i);
v.push_back(sol);}for (int i = 0; i <= rowIndex; i++) {
sol = C(rowIndex, i);
v.push_back(sol);
}Context
StackExchange Code Review Q#52028, answer score: 32
Revisions (0)
No revisions yet.