62. Unique Paths

来源:互联网 发布:淘宝达人资历怎么写 编辑:程序博客网 时间:2024/06/05 18:46

62 Unique Paths
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?
这里写图片描述

我自己写了一个很蠢的方法,没错,递归。。

class Solution {public:    int uniquePaths(int m, int n) {        vector<vector<int>> path(m,vector<int>(n,-1));        for(int i=0;i<m;++i)            path[i][0]=1;        for(int i=0;i<n;++i)            path[0][i]=1;        return countPath(path,m-1,n-1);    }    int countPath(vector<vector<int>>& x,int row,int col)    {        if(x[row][col]!=-1)            return x[row][col];        else        {            x[row][col]=countPath(x,row-1,col)+countPath(x,row,col-1);            return x[row][col];        }    }};

写到这里,我又想起了一个改编版,不用递归。
先放个图。
这里写图片描述

代码:

class Solution {public:    int uniquePaths(int m, int n) {        vector<vector<int>> path(m,vector<int>(n,-1));        for(int i=0;i<m;++i)            path[i][0]=1;        for(int i=0;i<n;++i)            path[0][i]=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];    }};

然而最优化的方法是?
对于一个m*n的矩阵来说,我们要到达右下角就必须要走(m+n)步路,其中往下走m,往右边走n。
也就是说在这(m+n)个格子里放置红格子m个,绿格子n个。就是排列组合问题。
这里写图片描述

64.Minimum Path Sum
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

跟上题没区别。。。主要是限制了只能向下或者向右走。。那就没什么难度了