您的位置:首页 > 其它

第十四周leetcode题

2017-05-30 18:33 176 查看
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?



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

Note: m and n will be at most 100.

题意为从地图的左上角第一格的起点走到右下角的最后一格的终点的所有走法的种数的和,并且只能往下走或者是往右走。显然第一排和第一列的格子的走法只有1种,即不断往右走和不断往下走。对于其他格子来说,由于只能往下走或往右走,因此到达那个格子的方法为从该格子的上面往下走一步或者从该格子的左边往右走一步,因此到达该格子的走法数便为上面的格子和左边的格子的走法的总数之和。于是就可以通过填表得出最终答案。
代码如下:

class Solution {

public:

    int uniquePaths(int m, int n) {

        int sq[m]
;

        for(int i=0;i<m;i++)

        {

            sq[i][0]=1;

        }

        

        for(int i=0;i<n;i++)

        {

            sq[0][i]=1;

        }

        

        for(int i=1;i<m;i++)

        {

            for(int j=1;j<n;j++)

            {

                sq[i][j]=sq[i-1][j]+sq[i][j-1];

            }

        }

        

        return sq[m-1][n-1];

    }

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