Simple for loop


  • 0
    K

    Javascript Code. Each time the code looks for the 1 row up, and left column to the left, to see how many ways does the user have to reach that point. The current block is a summation of the two, as the user can come from either of the two locations.

    /**
     * @param {number} m
     * @param {number} n
     * @return {number}
     */
    var uniquePaths = function(m, n) {
        let dp = [];
       // Initialize solution with 1, for whole  of the 0th column and 0th row 
       // as one can only move along a straight the line to the right or down
       // respectively to reach any block in the 0th row or 0th column.
        for(let i = 0; i < m; i++) {
            dp[i] = [];
            dp[i][0] = 1;
        }
        for(let i = 0; i < n; i++)
            dp[0][i] = 1;
        for(let i = 1; i < m; i++ ) {
            for(let j = 1; j < n; j++ ) {
                dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m-1][n-1];
    };
    
    

Log in to reply
 

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