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.

解法:

解法1:我的解法采用的是高中所学的排列与组合。m*n格中移动的步数总和为m+n-2,题目的答案即为在m+n-2步中,向下的步m-1步的取法,C(m-1,m+n-2)。代码如下:
 public:
    int uniquePaths(int m, int n) {
        allstep=m+n-2;
        minnum = min(m-1,n-1);//取m-1,和n-1中的较小者,简化运算。
        if(1 == m || 1 == n)
        {
            return 1;
        }
        else{
            for ( int i = 0; i < minnum; i++)
            {
                Upresult *= allstep - i;//计算m-1,或者n-1,插入到allstep中的不同排列。
                Downresult *= i + 1;//计算m-1,或者n-1,的全排列。
            }
            return result = Upresult / Downresult;//结果
        }
    }
private:
    int allstep=0;
    int minnum=0;
   /*
    *关键地方,想到排列组合的人不在少数,但是能考虑连乘结果会超过"int"取值范围的人应该不多。
    *笔者提交返回结果为(m,n)=(10,10)出错,考虑了很久,最后到编译器里才发现Upresult超过了"int"的取值范围,因此采用long long型。
    */
    long long Upresult=1;
    long long Downresult=1;
    int result=0;
};

未完待续:

这题还存在,动态规划,和深度优先搜索的解法,但是笔者还没有弄懂,弄明白之后在续上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值