[leetcode]Unique Paths

来源:互联网 发布:淘宝店铺运营教程视频 编辑:程序博客网 时间:2024/06/18 12:59

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?


Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

题意:一个机器人在m X n的矩阵的左上角, 且每次只能向下或向右移动。问如果要移动最右下角有多少种方案?

解题思路:动态规划, 状态转移方程 dp[i][j] = dp[i + 1][j] + dp[i][j + 1], 数组最右边一列,及数组最下边一行初始化为1.

class Solution {public:    int uniquePaths(int m, int n) {    // Note: The Solution object is instantiated only once and is reused by each test case.    //动态规划    //一个机器人在m*n的格子左上角要到右下角去,只能向右或是向下移动,列出所有可走的路线数    //定义一个二维数组,用容器vector模拟,数组最下及最右一排为一,然后从右下方做叠加到左上方    vector<vector<int> > v;    vector<int> tmp(n, 1);        for (int i = 0; i < m; i++){    v.push_back(tmp);    }    //处理非最右及最下的数据项    for (int i = m - 2; i >= 0; i--)    {    for (int j = n - 2; j >= 0; j--)    {        //当前数据 等于 右面与下面数据之和    v[i][j] = v[i + 1][j] + v[i][j + 1];    }    }        //返回总路径数    return v[0][0];    }};


0 0
原创粉丝点击