Using c++ recursion to solve this problem


  • 0
    S
    class Solution {
    public:
        vector<int> getRow(int rowIndex) {
            vector<int> cur;
            cur.push_back(1);
            if(rowIndex <= 0) return cur;
        
            vector<int> res = getRow(rowIndex -1);
            for(int i=1;i<rowIndex;i++){
                int num = res[i-1] + res[i];
                cur.push_back(num);
            }
        
            cur.push_back(1);
            return cur;
        }
    };

  • 0
    L

    I use recursion too. 4 ms.

    vector<int> getRow(int rowIndex) {
        vector<int> result;
        
        if (rowIndex == 0) {
            result.push_back(1);
            
            return result;
        } else {
            vector<int> vec = getRow(rowIndex - 1);
            result.push_back(1);
            for (size_t i = 0; i < vec.size() - 1; i++) {
                result.push_back(vec[i] + vec[i+1]);
            }
            result.push_back(1);
        }
    }

Log in to reply
 

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