Created
September 14, 2014 20:54
-
-
Save walkingtospace/77abc84ea41c14a3439c to your computer and use it in GitHub Desktop.
unique-paths with dynamic programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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