Skip to content

Instantly share code, notes, and snippets.

@walkingtospace
Created September 14, 2014 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkingtospace/77abc84ea41c14a3439c to your computer and use it in GitHub Desktop.
Save walkingtospace/77abc84ea41c14a3439c to your computer and use it in GitHub Desktop.
unique-paths with dynamic programming
https://oj.leetcode.com/problems/unique-paths/
/*
let's count the number of cases:
m,n=00/10/01 .. 1
m,n=1,1 1
m,n=1,2 1
m,n=1,3 1
m,n=2,1 1
m,n=2,2 (2,1) + (1,2) = 2
m,n=2,3 (2,2) + (1,3) = 3
m,n=2,4 (2,3) + (1,4) = 4
m,n=3,2 (2,2) + (3,1) = 5
m,n=3,3 (3,2) + (2,3) = 6
m,n=3,4 (3,3) + (2,4) = 6+4 = 10
...
so, if mn == ij then mn = (i,j-1) + (i-1,j).
go recursive solution with loops, not function call because of memory/speed efficiency
O(mn) solution : using 2 forloops to calculate map[m][n] from 1,1 to m,n
*/
class Solution {
public:
int uniquePaths(int m, int n) {
if(m <= 1 || n <= 1) {
return 1;
}
vector<int> col(n,1);
vector<vector<int>> map;
for(int i=0; i<m ; ++i) {
map.push_back(col);
}
for(int i=1 ; i<m; i++) {
for(int j=1 ; j<n; ++j) {
map[i][j] = map[i-1][j]+map[i][j-1];
}
}
return map[m-1][n-1];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment