My C++ Solution with O(n) time and O(1) space


  • 1
    T

    `
    class Solution {
    public:
    //C(n,k)=(n-k+1)/(k) * C(n,k-1);
    vector<int> getRow(int rowIndex) {
    vector<int> pt;
    if(rowIndex < 0) {
    return pt;
    }

        //init: C(n,0)=1                    
        pt.push_back(1);                    
                                            
        int k = 1;    
        long temp;
        for(; k <= rowIndex/2; k++) {      
            //may be overflow
            temp = (long)pt[(size_t)k-1] * (rowIndex-k+1) / (k);
            pt.push_back((int)temp);
        }                                   
        size_t flag = rowIndex & 0x1 ? 1 : 2;                                   
        for(size_t count = flag; count <= (size_t)k; count++) {
            pt.push_back(pt[(size_t)k-count]);
        }                                   
                                            
        return pt;
    }
    

    };

    `


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.