Leetcode62.Unique_Paths

一开始以为是DFS,代码超时后,发现没认真审题。只能向下和向右移动。运用我在Leetcode70.Climbing_Stairs中分析的重复数全排列,对于m*n的区域,需要(m-1)次向右和(n-1)次向下,不同到达终点的方法有 A m + n 2 m + n 2 A m 1 m 1 A n 1 n 1 \frac{A_{m+n-2}^{m+n-2}}{A_{m-1}^{m-1}*A_{n-1}^{n-1}} 中。
p.s.这道题比较“算法”的解决方法是用动态规划解决,详细分析见Leetcode63.Unique_Path_II
时间复杂度:O(m+n)
C++代码:

class Solution {
public:
	int uniquePaths(int m, int n) {
		if (m >= n)
		{
			--m;
			--n;
			int result = 1;
			int j = 2;
			for (int i = m + n; i > m; i--)
			{
				result *= i;
				while (j <= n && result / j * j == result)
				{
					result /= j;
					j++;
				}
			}
			while (j <= n)
			{
				result /= j;
				j++;
			}
			return result;
		}
		else
			return uniquePaths(n, m);
	}
};

猜你喜欢

转载自blog.csdn.net/qq_42263831/article/details/82900393