1636. [算法课分支限界法]硬币问题

java:

public int change(int amount, int[] coins) { int n = coins.length, m = amount; if (amount == 0) return 1; if(n == 1) { if (coins[0] == amount) return 1; if (coins[0] >= amount) return 0; } int[][] dp = new int[n+1][m+1]; //base case for(int i = 0; i < n+1; i++){ dp[i][0] = 1; } for (int i = 1; i < n+1; i++){ for (int j = 1; j < m+1; j++){ //当前值等于不放入当前硬币金额达到amount的情况,和当入当前硬币金额达到的情况 if (j - coins[i-1] >= 0){ dp[i][j] = dp[i-1][j] + dp[i][j-coins[i-1]]; }else { dp[i][j] = dp[i-1][j]; } } } return dp[n][m]; }

//1.dp数组 //2.base case //3.求状态转移方程(数学归纳法 或 根据实际情况推导,如背包问题分为放入和不放入两种情况)