码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Unique Paths

时间:2014-11-04 17:30:56      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:algorithm   leetcode   

题目描述:

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?


思路:开一个m*n的数组pathCount,pathCount[i][j]表示从点(i,j)走到终点有多少种走法。将最后一列和最后一行的元素初始化为1(因为如果robot走到最后一列或者最后一行,将只能以一种方式走到终点)。根据pathCount[i][j]=pathCount[i+1][j]+pathCount[i][j+1],算出pathCount[0][0],即得到结果。


代码:

<pre name="code" class="cpp">int uniquePaths(int m, int n) {
        int ** pathCount = (int**)(malloc(sizeof(int*)*m));
    int i,j;
    for(i = 0;i < m;i++)
        pathCount[i] = (int*)malloc(sizeof(int)*n);
    pathCount[m-1][n-1] = 0;
    for(i = 0;i < n;i++)
        pathCount[m-1][i] = 1;
    for(i = 0;i < m;i++)
        pathCount[i][n-1] = 1;
    for(i = m-2;i >= 0;i--)
        for(j = n-2;j >=0;j--)
            pathCount[i][j] = pathCount[i][j+1] + pathCount[i+1][j];
    return pathCount[0][0];
    }




LeetCode:Unique Paths

标签:algorithm   leetcode   

原文地址:http://blog.csdn.net/yao_wust/article/details/40786235

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!