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

[LeetCode] 62. Unique Paths

2018-03-07 21:45 411 查看
题:https://leetcode.com/problems/unique-paths/description/
题目
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).How many possible unique paths are there?


思路
动态规划问题,规划模型:
Since the robot can only move right and down, when it arrives at a point, there are only two possibilities:
It arrives at that point from above (moving down to that point);
It arrives at that point from left (moving right to that point).
Thus, we have the following state equations: suppose the number of paths to arrive at a point 
(i, j)
 is denoted as 
P[i][j]
, it is easily concluded that 
P[i][j] = P[i - 1][j] + P[i][j - 1]
.
initialize 
P[0][j] = 1, P[i][0] = 1
 for all valid 
i, j
. Note the initial value is 
1

这里坐标从(0,0)开始
Codeclass Solution {
public:
int uniquePaths(int m, int n) {
//vector<vector<int> > path(m, vector<int> (n, 1));
int path[m]
;
for(int j = 0;j<m;j++) path[j][0] = 1;
for(int j = 0;j<n;j++) path[0][j] = 1;
for (int i = 1; i < m; i++)
for (int j = 1; j < n; j++)
path[i][j] = path[i - 1][j] + path[i][j - 1];
return path[m - 1][n - 1];
}
};开始 用递归的方法做,出现了 超时的问题。下次该类问题 转为 状态转移的,应该多考虑用DP方式解决。
Codeclass Solution {
public:
int pathnums(int m,int n){
if(m==1||n==1){
return 1;
}
int sum = 0;
for(int i = 1; i<=m-1;i++){
sum+=pathnums(i,n-1);

}
for(int j = 1; j<=n-1 ;j++){
sum+=pathnums(m-1,j);

}
return sum;
}

int uniquePaths(int m, int
aa4c
n) {
return pathnums(m,n);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: