leecode 解题总结:62. Unique Paths

来源:互联网 发布:微信一键传图软件 编辑:程序博客网 时间:2024/06/03 18:22
#include <iostream>#include <stdio.h>#include <vector>using namespace std;/*问题: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?Above is a 3 x 7 grid. How many possible unique paths are there?Note: m and n will be at most 100.分析:程序员面试金典的一道题目。这是递归。可以从后向前分析最后的位置可能是从左边或者上边过来的。设dp[i][j]表示到达位置(i,j)的无重复路径个数,dp[i][j] = dp[i-1][j] + dp[i][j-1]其中dp[i][0] = 1,dp[0][j]=1目标求dp[m-1][n-1]输入:2(行数) 2(列数)1 11 33 13 23 3输出:211136关键:1 既然是dp,可以直接迭代来做,不需要递归*/class Solution {public:int dfs( vector< vector<int> >& paths , int row , int col ){if(paths.empty() || row < 0 || col < 0){return 0;}//如果当前位置求得值,直接返回if(paths.at(row).at(col) != 0){return paths.at(row).at(col);}//没有求出位置,利用状态迁移方程计算else{paths.at(row).at(col) = dfs(paths , row - 1 , col) + dfs(paths , row , col - 1);return paths.at(row).at(col);}}    int uniquePaths(int m, int n) {//参数检查if(m <= 0 || n <= 0){return 0;}//初始化边界值为1vector< vector<int> > paths( m , vector<int>(n , 1) );//动态规划查找//int result = dfs(paths , m - 1 , n - 1);//动态规划直接地推,无需递归for(int i = 1; i < m ; i++){for(int j = 1 ; j < n ; j++){paths[i][j] = paths[i-1][j] + paths[i][j-1];}}return paths.at(m-1).at(n-1);    }};void process(){ Solution solution; int row; int col; while(cin >> row >> col ) { int result = solution.uniquePaths(row , col); cout << result << endl; }}int main(int argc , char* argv[]){process();getchar();return 0;}

0 0
原创粉丝点击