您的位置:首页 > 产品设计 > UI/UE

LeetCode之Unique Paths

2015-09-27 16:36 330 查看
/*备忘录法。*/
class Solution {
public:
int uniquePaths(int m, int n) {
if(m < 1 || n < 1) return 0;
vector<vector<int> > path(m+1, vector<int>(n+1, 0));
for(int i = 1; i <= m; ++i){
for(int j = 1; j <= n; ++j){
path[i][j] = dfs(i, j, path);
}
}
return path[m]
;
}

int dfs(int row, int col, vector<vector<int> > &path){
if(row == 1 || col == 1) return 1;
else return get(row-1, col, path) + get(row, col-1, path);
}

int get(int row, int col, vector<vector<int> > &path){
if(row == 1 || col == 1) return 1;
if(path[row][col] > 0) return path[row][col];
else return dfs(row, col, path);
}
};

/*动态规划法。*/
class Solution {
public:
int uniquePaths(int m, int n) {
if(m < 1 || n < 1) return 0;
vector<int> path(n+1, 0);
path[1] = 1;
for(int i = 1; i <= m; ++i){
for(int j = 2; j <= n; ++j){
path[j] = path[j] + path[j-1];
}
}
return path
;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: