1. 程式人生 > 其它 >LeetCode_62_不同路徑

LeetCode_62_不同路徑

技術標籤:LeetCode學習之路leetcode

題目連結

解題思路

  • 組合數學中的格路模型
  • 從左上角到右下角的過程中,我們需要移動m + n - 2次,其中有m - 1次向下移動,n - 1次向右移動。
  • 因此路徑的總數 = C ( m + n − 2 , m − 1 ) C(m+n-2,m-1) C(m+n2,m1)

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)); } }