Unique Paths
阿新 • • 發佈:2017-05-20
方法 color pan log tor ret pri || public
方法一:直接使用備忘錄
class Solution { public: int uniquePaths(int m, int n) { fm = vector<vector<int>>(m, vector<int>(n, 0)); fm[0][0] = 1; return dfs(m-1, n-1); } private: vector<vector<int>> fm; int dfs(int m, int n) {if(m < 0 || n < 0) return 0; if(m == 0 || n == 0) return 1; if(fm[m][n] > 0) return fm[m][n]; else return fm[m][n] = dfs(m-1, n) + dfs(m, n-1); } };
方法二:使用動態規劃的方法
class Solution { public: int uniquePaths(intm, int n) { vector<vector<int>> fm = vector<vector<int>>(m, vector<int>(n,0)); for(int i=0; i<m; ++i) { for(int j=0; j<n; ++j) { if(i == 0 || j == 0) fm[i][j] = 1;else fm[i][j] = fm[i-1][j] + fm[i][j-1]; } } return fm[m-1][n-1]; } };
Unique Paths