码迷,mamicode.com
首页 > 移动开发 > 详细

[CareerCup] 9.2 Robot Moving 机器人移动

时间:2015-09-18 00:47:15      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

 

9.2 Imagine a robot sitting on the upper left corner of an X by Y grid. The robot can only move in two directions: right and down. How many possible paths are there for the robot to go from (0,0) to (X,Y)?
 FOLLOW UP
 Imagine certain spots are "off limits," such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right.

 

LeetCode上的原题,请参见我之前的博客Unique Paths 不同的路径Unique Paths II 不同的路径之二

 

解法一:

class Solution {
public:
    int getPath(int x, int y) {
        vector<int> dp(y + 1, 1);
        for (int i = 1; i <= x; ++i) {
            for (int j = 1; j <= y; ++j) {
                dp[j] += dp[j - 1];
            }
        }
        return dp[y];
    }
};

 

解法二:

class Solution {
public:
    int getPath(int x, int y) {
        double num = 1, denom = 1;
        int small = x < y ? x : y;
        for (int i = 1; i <= small; ++i) {
            num *= x + y - i + 1;
            denom *= i;
        }
        return (int)(num / denom);
    }
};

 

[CareerCup] 9.2 Robot Moving 机器人移动

标签:

原文地址:http://www.cnblogs.com/grandyang/p/4817962.html

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