LeetCode_62_不同路徑
阿新 • • 發佈:2020-12-10
技術標籤:LeetCode學習之路leetcode
題目連結
解題思路
- 組合數學中的格路模型
- 從左上角到右下角的過程中,我們需要移動
m + n - 2
次,其中有m - 1
次向下移動,n - 1
次向右移動。 - 因此路徑的總數 = C ( m + n − 2 , m − 1 ) C(m+n-2,m-1) C(m+n−2,m−1)
AC程式碼
class Solution {
public int uniquePaths(int m, int n) {
long ans = 1;
for (int x = n, y = 1; y < m; ++x, ++y)
ans = ans * x / y;
return (int) ans;
}
}
本地測試程式碼
package com.company;
public class Solution_62 {
public static int uniquePaths(int m, int n) {
long ans = 1;
for (int x = n, y = 1; y < m; ++x, ++y)
ans = ans * x / y;
return (int) ans;
}
public static void main(String[] args) {
System.out.println(uniquePaths(3, 7));
System.out.println(uniquePaths(3, 2));
}
}