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); } };
时间: 2024-10-14 14:17:02