動態規劃算法一般遵循一套固定的流程:遞歸的暴力解法 -> 帶備忘錄的遞歸解法 -> 非遞歸的動態規劃解法。
package dynamic_programming;
/**
* @program: Aglorithm
* @Date: today
* @Author: Kyrie
* @Description:
*
* 動態規劃小結
*/
public class Dynamic_Programming_Summary {
}
- 零錢兌換
給定不同面額的硬幣 coins 和一個總金額 amount。編寫一個函數來計算可以湊成總金額所需的最少的硬幣個數。如果沒有任何一種硬幣組合能組成總金額,返回 -1。
// 暴力遞歸
public static int coinsChange(int[] arr, int amount){
//遞歸終止條件
if (amount == 0) return 0;
if (amount < 0) return -1;
//初始化最小值min
int min = Integer.MAX_VALUE; //判斷最小值是否更新,若沒有更新則說明不能湊成amount
for (int i = 0; i < arr.length; i++) {
if (amount - arr[i] < 0) continue;
int coins = coinsChange(arr, amount - arr[i]);
if (coins == -1) continue;
min = Math.min(coins + 1, min);
}
return min == Integer.MAX_VALUE ? -1 : min;
}
//備忘錄方式
public static HashMap<Integer, Integer> map = new HashMap<>(); //相當於備忘錄的功能
public static int coinsReplace02(int[] arr, int target){
//遞歸終止條件
if(target == 0)
return 0;
if (target < 0)
return -1;
if (map.containsKey(target))
return map.get(target); //相當於備忘錄的功能
int min = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) {
int diff = target - arr[i];
int count = coinsReplace02(arr, diff); //min
if (count == -1) //使用該硬幣不能構成target
continue; //跳過該硬幣
//更新min
int num = 1 + count; //使用該硬幣 num代表使用的coins數量
if (num < min){
min = num;
map.put(target, min);
}
}
if (min == Integer.MAX_VALUE){ // 不能湊成
return -1;
}else
return min;
}
//動態規劃
public int coinChange(int[] arr, int target) {
if (target < 0 || arr.length == 0)
return -1;
int[] dp = new int[target + 1];
for (int i = 1; i <= target; i++) {
int min = Integer.MAX_VALUE;
//int diff = -1;
for (int j = 0; j < arr.length; j++) {
int diff = i - arr[j];
if (diff >= 0 && dp[diff] != -1)
min = Math.min(min, dp[diff]);
//dp[i] = min == Integer.MAX_VALUE ? -1 : min + 1; //若min爲Integer.MAX_VALUE,則說明花掉的硬幣,不能湊成總金額
}
dp[i] = min == Integer.MAX_VALUE ? -1 : min + 1; //若min爲Integer.MAX_VALUE,則說明花掉的硬幣,不能湊成總金額
}
return dp[target];
}
執行用時 : 21 ms, 在Coin Change的Java提交中擊敗了91.32% 的用戶
內存消耗 : 35.1 MB, 在Coin Change的Java提交中擊敗了98.57% 的用戶
- 最小路徑和
package dynamic_processing;
public class Demo_dp02 {
/**
* @Author Kyrie
* @Description
* @Date today
* 最小路徑和:
* 給定一個包含非負整數的 m x n 網格,請找出一條從左上角到右下角的路徑,
* 使得路徑上的數字總和爲最小。每次只能向下或者向右移動一步。
**/
//遞歸方式
public int minPathSum02(int[][] grid) {
return process(grid, 0, 0);
}
public int process(int[][] arr, int i, int j) {
if (i == arr.length - 1 && j == arr[0].length - 1)
return arr[i][j];
if (i == arr.length - 1)
return arr[i][j] + process(arr, i, j + 1);
if (j == arr[0].length - 1)
return arr[i][j] + process(arr, i + 1, j);
int right = process(arr, i, j + 1);
int down = process(arr, i + 1, j);
return arr[i][j] + Math.min(right, down);
}
//備忘錄-方式 可以模仿使用HashMap來存儲未計算的值,並判斷是否該值已經存在
//動態規劃
public static int minPathSum(int[][] arr) {
if (arr == null || arr.length == 0 || arr[0] == null || arr[0].length == 0) {
return 0;
}
int row = arr.length;
int col = arr[0].length;
int[][] dp = new int[row][col];
dp[row - 1][col - 1] = arr[row - 1][col - 1];
for (int j = col - 2; j >= 0; j--) {
dp[row - 1][j] = dp[row - 1][j + 1] + arr[row - 1][j];
}
for (int i = row - 2; i >= 0; i--) {
dp[i][col - 1] = dp[i + 1][col - 1] + arr[i][col - 1];
}
for (int i = row - 2; i >= 0; i--) {
for (int j = col - 2; j >= 0; j--) {
dp[i][j] = arr[i][j] + Math.min(dp[i + 1][j], dp[i][j + 1]);
}
}
return dp[0][0];
}
//進一步優化,使用空間複雜度爲O(N)
}
- 最長相同子字符串
package dynamic_processing;
public class Demo_dp03 {
/**
* 最長相同子字符串
* 輸入
* String X = "ATCTGAT";
* String Y = "TGCATA";
* 輸出
* String Z = "TCTA"; //4
* <p>
* 分析:最長相同子字符串可通過小一些的最長相同子字符串獲得。
* 尾部的字符,兩種情況:1.X最後沒有字母T,此時尾部字母相同;
* 2.Y最後沒有字母A,此時尾部字母相同;
* 若計算出上述兩個最長相同子字符串的答案,則其中較長的相同子字符串爲X和Y的
* 最長相同子字符串。
* <p>
* 對於兩字符串的字尾相同時,可通過短一些的最長相同子字符串獲取,之後在尾部加上
* 共同擁有的字母。
* <p>
* 利用數學式子描述大問題的最優解和小問題的最優解的關係:
* c[i,j]代表並存儲其相關小問題的最優解的長度,即c[i,j]代表字串X中前面i個字符和
* 字符串Y中前面的j個字符所形成的最長相同子字符串的長度。
* 0, if i = 0 or j = 0
* c[i,j] = c[i-1][j-1] + 1, if i,j > 0 and Xi = Yj,
* max(c[i-1][j], c[i][j-1]), if i,j > 0 and Xi != Yj
*/
public static int findlongString(String str1, String str2) {
if (str1 == null || str2 == null || str1.length() == 0 || str2.length() == 0)
return 0;
int row = str1.length();
int col = str2.length();
int[][] dp = new int[row + 1][col + 1]; // 增加一行和一列省去初始化邊界,初始化爲0
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= col; j++) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) //當字符相等時
dp[i][j] = dp[i - 1][j - 1] + 1;
else {
if (dp[i][j - 1] >= dp[i - 1][j])
dp[i][j] = dp[i][j - 1];
else
dp[i][j] = dp[i - 1][j];
}
}
}
//打印dp
/*
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[0].length; j++) {
System.out.print(dp[i][j] + " ");
}
System.out.println();
}*/
return dp[row][col];
}
public static void main(String[] args) {
String X = "ATCTGAT";
String Y = "TGCATA";
System.out.println(findlongString(X, Y)); // 4
}
}
- 安排員工聚會問題
package dynamic_processing;
public class Demo_dp04 {
/**
* @Author Kyrie
* @Description
* @Date today
* @Param 員工數N, happy數組
* happyp[v] 每一個節點v將其快樂指數存於happy[v]中。
* sumofhappy[v] 以v爲根的部門(小樹)的最大快樂指數
* children[v,j] 若children[v,j]返回true,則代表節點v爲j的父節點
* @return 返回最大happy值
*
* 最優子結構判斷:
* 檢查大問題的最優解可以利用小問題的最優解組合得到
* 注意:
* 若在公司找出N位員工是大問題,則小問題應該是什麼?怎樣的小問題的最優解對解大問題有幫助?
* 比如,已知N-1位員工的小問題的最優解,好像對找到N位員工大問題的解幫助不大。因爲,沒有考慮數據結構之間的關係。
* 原數據的數據結構是一顆樹tree,因此小問題應該是小樹或子樹!!
*
* 最優子結構分析:
* 1.若根節點考慮,則最大值依賴於其所有子節點的最大值之和
* 2.若根節點不考慮,則最大值依賴於其所有孫節點的最大值之和
*
* 描述大問題與子問題之間的數學式子:
* 若以v爲根的部門的最大值存儲於sumofhappy(v)中。當v是葉節點時,sumofhappy(v) = happy(v)。
* 當v不是葉節點時,假設其子節點爲ci,其孫節點爲sj。可用下列式子描述大問題與子問題之間的數學關係:
* sumofhappy(v) = Max{sumofhappy(c1)+...+sumofhappy(ci); happy(v)+sumofhappy(s1)+...+sumofhappy(sj)};
* 即:sumofhappy(v) = Max{};
**/
}
-
單詞拆分
給定一個非空字符串 s 和一個包含非空單詞列表的字典 wordDict,判定 s 是否可以被空格拆分爲一個或多個在字典中出現的單詞。說明:拆分時可以重複使用字典中的單詞。你可以假設字典中沒有重複的單詞。
-
示例 1:
輸入: s = “leetcode”, wordDict = [“leet”, “code”]
輸出: true
解釋: 返回 true 因爲 “leetcode” 可以被拆分成 “leet code”。 -
示例 2:
輸入: s = “applepenapple”, wordDict = [“apple”, “pen”]
輸出: true
解釋: 返回 true 因爲 “applepenapple” 可以被拆分成 “apple pen apple”。
注意你可以重複使用字典中的單詞。 -
示例 3:
輸入: s = “catsandog”, wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
輸出: false
-
class Solution {
//動態規劃
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> wordDictSet = new HashSet(wordDict); //構造一個包含指定 collection 中的元素的新set
boolean[] dp = new boolean[s.length() + 1]; // 初始化均爲false
dp[0] = true;
for (int i = 1; i <= s.length(); i++) { // 字符串的狀態
for (int j = 0; j < i; j++) { // 從start開始到end之間,形成的字符串是否存在於字典中,start++, end不變
if (dp[j] && wordDictSet.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
/*
for (boolean b : dp)
System.out.print(b + " "); //true false false false true false false false true
*/
return dp[s.length()];
}
}
- 最長迴文子串
package dynamic_processing;
public class Demo_dp06 {
/**
* 最長迴文子串(動態規劃版)
* 給定一個字符串s,找到s中最長的迴文子串。你可以假設s的最大長度爲 1000。
*
* 示例 1:
* 輸入: "babad"
* 輸出: "bab"
* 注意: "aba" 也是一個有效答案。
*
* 示例 2:
* 輸入: "cbbd"
* 輸出: "bb"
* 暴力法將選出所有子字符串可能的開始和結束位置,並檢驗它是不是迴文。
* 動態規劃就是優化暴力法的手段:首先初始化一字母和二字母的迴文,然後找到所有三字母迴文,並依此類推…
*
*/
public static String longestPalindrome(String s) {
int len = s.length();
if(len == 0){
return "";
}
char[] sToArray = s.toCharArray();
boolean[][] mem = new boolean[len][len];
int maxLen = 1;
int fromIndex = 0;
int toIndex = 1;
// 初始化條件
for(int i = 0; i < len; ++i){
mem[i][i] = true;
if(i + 1 < len && sToArray[i] == sToArray[i + 1]){
mem[i][i + 1] = true;
maxLen = 2;
fromIndex = i;
toIndex = i + 1 + 1;
}
}
// 執行dp
for(int i = 2; i < len; ++i){
for(int j = 0; j < i - 1; ++j){
mem[j][i] = mem[j + 1][i - 1] && sToArray[j] == sToArray[i];
if(mem[j][i] && i - j + 1 > maxLen){
maxLen = i - j + 1;
fromIndex = j;
toIndex = i + 1;
}
}
}
return s.substring(fromIndex, toIndex);
}
}