Javascript, solution-sharing, Easy to understand


  • 1
    C

    javascript

    /**
     * English poor, use google translate.
     * Information: The first number of the n-th row of Pascal's triangle is 1, the second number is 1 × (n-1), the third number is 1 × (n-1) × (n-2) / 2, paragraph number four 1 × (n-1) × (n-2) / 2 × (n-3) / 3 ... and so on.
     * Define an array, the array element is defined as an array of resort
     */
    solution A: 120ms
    var generate = function(numRows) {
    	var result = new Array(numRows);
    	for(var i=0; i<numRows; i++){
    		result[i] = [];
    		for(var j=0; j<=i; j++){
    			result[i].push(triangle(i, j));
    		}
    	}
    	function triangle(m, n) {
    		if(n===0) {return 1;}
    		else if(m==n) { return 1; }
    		else { return ((m+1-n)/n)*arguments.callee(m, n-1); } //	Equivalent to: else { return ((m+1-n)/n)*triangle(m, n-1); }
    	}
    	return result;
    };
    solution B: 108ms
    var generate = function(numRows) {
        var result = [];
        for(var i=0; i<numRows; i++){
            result[i] = [];
        }
        for(i=0; i<numRows; i++){
            result[i][0] = result[i][i] = 1;
        }
        for(i=2; i<numRows; i++){
            for(var j=1; j<i; j++){
                result[i][j] = result[i-1][j-1] + result[i-1][j];
            }
        }
        return result;
    };

Log in to reply
 

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