My JavaScript Solution


  • 0
    S

    Define first row first, and base on first row to generate next row:

    var generate = function(numRows) {
        if (numRows < 1) return [];
    
        var res = [];
        res[0] = [1];
        for (var i = 1; i < numRows; i++) {
            res[i] = next(res[i - 1], i);
        }
        return res;
    
     //function to generate next row array
        function next(a, i) {
            var nextrow = [];
            for (var j = 0; j < i + 1; j++) {
                //check if the element in current array is the 
                // first or last by checking previous row array
                nextrow[j] = (!!a[j - 1] && !!a[j]) ? (a[j - 1] + a[j]) : 1;
            }
            return nextrow;
        }
    };
    
    

  • 1

    @shao like this:

    var generate = function(numRows) {
        var result = [];
        for (var i = 0, l = numRows; i < l; i++) {
            var arr = [];
            arr[0] = arr[i] = 1;
            for (var j = 1; j < i; j++) {
                arr[j] = result[i - 1][j] + result[i - 1][j - 1];
            }
            result.push(arr);
        }
        return result;
    };

Log in to reply
 

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