題目來源:
https://leetcode.com/problems/unique-paths/
題意分析:
給定兩個整型m,n。判斷從一個m×n的矩陣裡面,從(0,0)走到(m-1,n-1)一共有多少種法(隻能往下和往右走)。
題目思路:
這可以看成一個組合問題。從(0,0)到(m-1,n-1)一共要走m - 1次向下,n-1次向右。也就是在n + m - 2次中選出m-1次向下,也就是C(m + n - 2,m-1)。
代碼(python):
1 import math
2 class Solution(object):
3 def uniquePaths(self, m, n):
4 """
5 :type m: int
6 :type n: int
7 :rtype: int
8 """
9 ans = 1;tmp = 1;m -= 1;n -= 1
10 t = min(m,n)
11 i = 0
12 while i < t:
13 ans *= (m + n - i)
14 tmp *= (t - i)
15 i += 1
16 return ans /tmp
View Code
轉載請注明出處:http://www.cnblogs.com/chruny/p/5008210.html