1. 程式人生 > 實用技巧 >[程式設計題] nk [爬樓梯2-大數運算]

[程式設計題] nk [爬樓梯2-大數運算]

[程式設計題] nk 爬樓梯2-大數運算

題目

輸入輸出

Java程式碼

方法:動態規劃

import java.util.*;
import java.math.BigInteger;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        BigInteger res = dp(n);
        System.out.println(res);
    }
    
    //動態規劃
    /*這個題數大的話溢位,所以用bigInteger*/
    public static BigInteger dp(int n) {
        if(n<=2){return BigInteger.valueOf(1);}  //剪枝
        //n>=3的情況使用dp處理
        BigInteger[] dp =  new BigInteger[n+1];
        dp[1] = BigInteger.valueOf(1);  //n=1的時候只能走1個臺階
        dp[2] = BigInteger.valueOf(1);  //n=2 的時候只能每次走一個臺階這一種方法
        dp[3] = BigInteger.valueOf(2);  //n=3 的時候一次3個臺階,一次1個臺階走共2種辦法
        for(int i=4;i<=n;i++){
            dp[i] = dp[i-1].add(dp[i-3]);  //相當於dp[i] = dp[i-1]+dp[i-2]);
        }
        return dp[n];
     }
}