Solution for kth row of Pascal's triangle for a job interview 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?

class Solution {
   public:
    long long C(int n, int r) {
       if(r &gt; n / 2) r = n - r; // because C(n, r) == C(n, n - r)
       long long ans = 1;
       int i;

       for(i = 1; i &lt;= r; i++) {
           ans *= n - r + i;
           ans /= i;
       }

       return ans;
   }

       vector&lt;int&gt; getRow(int rowIndex) {
           vector&lt;int&gt; v;
           long long sol;
           for(int i=0;i&lt;=rowIndex;i++)
           {sol=C(rowIndex,i);
           v.push_back(sol);}

          return v; 
       }
   };
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:


for(int i=0;i&lt;=rowIndex;i++)



should use some whitespace:

for (int i = 0; i &lt;= rowIndex; i++)


You already do this in other places, and it should be done everywhere.

Also, this:


for(int i=0;i&lt;=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 &lt;= rowIndex; i++) {
    sol = C(rowIndex, i);
    v.push_back(sol);
}