動態規劃問題的三種類型
阿新 • • 發佈:2020-09-19
1.求最值
交換硬幣 (lintcode 669)
public class CoinChange { public static void main(String[] args) { Solution solution = new CoinChange().new Solution(); System.out.println("solution.coinChange(new int[]{1, 2, 5}, 11) = " + solution.coinChange(new int[]{1, 2, 5}, 11)); } class Solution { public int coinChange(int[] A, int M) { int[] f = new int[M + 1]; f[0] = 0; for (int i = 1; i <= M; i++) { f[i] = Integer.MAX_VALUE; for (int j = 0; j < A.length; j++) { if (i >= A[j] && f[i - A[j]] != Integer.MAX_VALUE) { f[i] = Math.min(f[i - A[j]] + 1, f[i]); } } System.out.printf("f[%s] = %s\n", i, f[i]); } if (f[M] == Integer.MAX_VALUE) { f[M] = -1; } return f[M]; } } }
2.求總數
機器人路徑(lintcode 114)
public class UniquePath { public static void main(String[] args) { Solution solution = new UniquePath().new Solution(); System.out.println(solution.uniquePath(1, 1)); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int uniquePath(int m, int n) { int[][] dp = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0) { dp[i][j] = 1; } else { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } } return dp[m - 1][n - 1]; } } //leetcode submit region end(Prohibit modification and deletion) }
3.存在型
跳躍遊戲(lintcode 116)
public class JumpGame { public static void main(String[] args) { Solution solution = new JumpGame().new Solution(); } class Solution { public boolean canJump(int[] A) { int n = A.length; boolean[] f = new boolean[n]; f[0] = true; for (int j = 1; j < n; j++) { f[j] = false; for (int i = 0; i < j; i++) { if (f[i] && i + A[i] >= j) { f[j] = true; break; } } } return f[n - 1]; } } }
233