Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created June 3, 2015 18:47
Show Gist options
  • Save cangoal/9e5fc3e61f57e531e9bc to your computer and use it in GitHub Desktop.
Save cangoal/9e5fc3e61f57e531e9bc to your computer and use it in GitHub Desktop.
LeetCode - Unique Paths
//
public int uniquePaths(int m, int n) {
if(m<1 || n<1) return 0;
if(m==1 || n==1) return 1;
int[][] ret = new int[m][n];
for(int i=0; i<m; i++){
ret[i][0] = 1;
}
for(int i=0; i<n; i++){
ret[0][i] = 1;
}
for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
ret[i][j] = ret[i-1][j] + ret[i][j-1];
}
}
return ret[m-1][n-1];
}
// better solution: less space complexity
public int uniquePaths(int m, int n) {
if(m<=0 || n<=0)
return 0;
int[] res = new int[n];
res[0] = 1;
for(int i=0;i<m;i++)
{
for(int j=1;j<n;j++)
{
res[j] += res[j-1];
}
}
return res[n-1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment