My simple java DP solution with explanation

  • 0
    public class Solution {
    public int uniquePaths(int m, int n) {
        //s[i][j] denotes number of paths from top-left to (i,j)
        int[][] s = new int[m][n];
        s[0][0] = 1;
        for(int i=0;i<m;i++){
            for(int j =0;j<n;j++){
                //if destination is on the first row or first col, result is 1
                if(i == 0||j == 0) s[i][j] = 1;
                //destination on other nodes
                else s[i][j] = s[i-1][j]+s[i][j-1];
        return s[m-1][n-1];


Log in to reply

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