class066 一維動態規劃
算法講解066【必備】從遞歸入手一維動態規劃
code1 509斐波那契數列
// 斐波那契數
// 斐波那契數 (通常用 F(n) 表示)形成的序列稱為 斐波那契數列
// 該數列由 0 和 1 開始,后面的每一項數字都是前面兩項數字的和。
// 也就是:F(0) = 0,F(1) = 1
// F(n) = F(n - 1) + F(n - 2),其中 n > 1
// 給定 n ,請計算 F(n)
// 測試鏈接 : https://leetcode.cn/problems/fibonacci-number/
// 注意:最優解來自矩陣快速冪,時間復雜度可以做到O(log n)
// 后續課程一定會講述!本節課不涉及!
dp[i]:從F(i)的值
=1,i=1
=i+dp[i-1],i>=2
f1 遞歸
f2 從頂到底 記憶化搜索
f3 從底到頂
f4 空間優化
package class066;import java.util.Arrays;// 斐波那契數
// 斐波那契數 (通常用 F(n) 表示)形成的序列稱為 斐波那契數列
// 該數列由 0 和 1 開始,后面的每一項數字都是前面兩項數字的和。
// 也就是:F(0) = 0,F(1) = 1
// F(n) = F(n - 1) + F(n - 2),其中 n > 1
// 給定 n ,請計算 F(n)
// 測試鏈接 : https://leetcode.cn/problems/fibonacci-number/
// 注意:最優解來自矩陣快速冪,時間復雜度可以做到O(log n)
// 后續課程一定會講述!本節課不涉及!
public class Code01_FibonacciNumber {public static int fib1(int n) {return f1(n);}public static int f1(int i) {if (i == 0) {return 0;}if (i == 1) {return 1;}return f1(i - 1) + f1(i - 2);}public static int fib2(int n) {int[] dp = new int[n + 1];Arrays.fill(dp, -1);return f2(n, dp);}public static int f2(int i, int[] dp) {if (i == 0) {return 0;}if (i == 1) {return 1;}if (dp[i] != -1) {return dp[i];}int ans = f2(i - 1, dp) + f2(i - 2, dp);dp[i] = ans;return ans;}public static int fib3(int n) {if (n == 0) {return 0;}if (n == 1) {return 1;}int[] dp = new int[n + 1];dp[1] = 1;for (int i = 2; i <= n; i++) {dp[i] = dp[i - 1] + dp[i - 2];}return dp[n];}public static int fib4(int n) {if (n == 0) {return 0;}if (n == 1) {return 1;}int lastLast = 0, last = 1;for (int i = 2, cur; i <= n; i++) {cur = lastLast + last;lastLast = last;last = cur;}return last;}}
code2 983最低票價
// 最低票價
// 在一個火車旅行很受歡迎的國度,你提前一年計劃了一些火車旅行
// 在接下來的一年里,你要旅行的日子將以一個名為 days 的數組給出
// 每一項是一個從 1 到 365 的整數
// 火車票有 三種不同的銷售方式
// 一張 為期1天 的通行證售價為 costs[0] 美元
// 一張 為期7天 的通行證售價為 costs[1] 美元
// 一張 為期30天 的通行證售價為 costs[2] 美元
// 通行證允許數天無限制的旅行
// 例如,如果我們在第 2 天獲得一張 為期 7 天 的通行證
// 那么我們可以連著旅行 7 天(第2~8天)
// 返回 你想要完成在給定的列表 days 中列出的每一天的旅行所需要的最低消費
// 測試鏈接 : https://leetcode.cn/problems/minimum-cost-for-tickets/
dp[i]:以i…天的最低票價
=math.min(cost[k]+dp[j]),(k:3種方案,j:方案到期天數)
f1 遞歸 有重復調用
[3,4,9,20,50,...]0 1 2 3 41天 1天 1天 1天 f(4,)7天 1天 f(4,)30天 f(4,)
f2 記憶化搜索 帶緩存的搜索
f3 動態規劃
package class066;import java.util.Arrays;// 最低票價
// 在一個火車旅行很受歡迎的國度,你提前一年計劃了一些火車旅行
// 在接下來的一年里,你要旅行的日子將以一個名為 days 的數組給出
// 每一項是一個從 1 到 365 的整數
// 火車票有 三種不同的銷售方式
// 一張 為期1天 的通行證售價為 costs[0] 美元
// 一張 為期7天 的通行證售價為 costs[1] 美元
// 一張 為期30天 的通行證售價為 costs[2] 美元
// 通行證允許數天無限制的旅行
// 例如,如果我們在第 2 天獲得一張 為期 7 天 的通行證
// 那么我們可以連著旅行 7 天(第2~8天)
// 返回 你想要完成在給定的列表 days 中列出的每一天的旅行所需要的最低消費
// 測試鏈接 : https://leetcode.cn/problems/minimum-cost-for-tickets/
public class Code02_MinimumCostForTickets {// 無論提交什么方法都帶著這個數組 0 1 2public static int[] durations = { 1, 7, 30 };// 暴力嘗試public static int mincostTickets1(int[] days, int[] costs) {return f1(days, costs, 0);}// days[i..... 最少花費是多少 public static int f1(int[] days, int[] costs, int i) {if (i == days.length) {// 后續已經無旅行了return 0;}// i下標 : 第days[i]天,有一場旅行// i.... 最少花費是多少 int ans = Integer.MAX_VALUE;for (int k = 0, j = i; k < 3; k++) {// k是方案編號 : 0 1 2while (j < days.length && days[i] + durations[k] > days[j]) {// 因為方案2持續的天數最多,30天// 所以while循環最多執行30次// 枚舉行為可以認為是O(1)j++;}ans = Math.min(ans, costs[k] + f1(days, costs, j));}return ans;}// 暴力嘗試改記憶化搜索// 從頂到底的動態規劃public static int mincostTickets2(int[] days, int[] costs) {int[] dp = new int[days.length];for (int i = 0; i < days.length; i++) {dp[i] = Integer.MAX_VALUE;}return f2(days, costs, 0, dp);}public static int f2(int[] days, int[] costs, int i, int[] dp) {if (i == days.length) {return 0;}if (dp[i] != Integer.MAX_VALUE) {return dp[i];}int ans = Integer.MAX_VALUE;for (int k = 0, j = i; k < 3; k++) {while (j < days.length && days[i] + durations[k] > days[j]) {j++;}ans = Math.min(ans, costs[k] + f2(days, costs, j, dp));}dp[i] = ans;return ans;}// 嚴格位置依賴的動態規劃// 從底到頂的動態規劃public static int MAXN = 366;public static int[] dp = new int[MAXN];public static int mincostTickets3(int[] days, int[] costs) {int n = days.length;Arrays.fill(dp, 0, n + 1, Integer.MAX_VALUE);dp[n] = 0;for (int i = n - 1; i >= 0; i--) {for (int k = 0, j = i; k < 3; k++) {while (j < days.length && days[i] + durations[k] > days[j]) {j++;}dp[i] = Math.min(dp[i], costs[k] + dp[j]);}}return dp[0];}}
code3 91解碼方法
// 解碼方法
// 一條包含字母 A-Z 的消息通過以下映射進行了 編碼 :
// ‘A’ -> “1”
// ‘B’ -> “2”
// …
// ‘Z’ -> “26”
// 要 解碼 已編碼的消息,所有數字必須基于上述映射的方法,反向映射回字母(可能有多種方法)
// 例如,“11106” 可以映射為:“AAJF”、“KJF”
// 注意,消息不能分組為(1 11 06),因為 “06” 不能映射為 “F”
// 這是由于 “6” 和 “06” 在映射中并不等價
// 給你一個只含數字的 非空 字符串 s ,請計算并返回 解碼 方法的 總數
// 題目數據保證答案肯定是一個 32位 的整數
// 測試鏈接 : https://leetcode.cn/problems/decode-ways/
dp[i]:以i開始的[i…]的解碼方法個數
=0,s[i]==‘0’
=dp[i+1]+1
+=dp[i+2],s[i] s[i+1]構成合法解碼
f1 遞歸
f2 記憶化搜索
f3 動態規劃
package class066;import java.util.Arrays;// 解碼方法
// 一條包含字母 A-Z 的消息通過以下映射進行了 編碼 :
// 'A' -> "1"
// 'B' -> "2"
// ...
// 'Z' -> "26"
// 要 解碼 已編碼的消息,所有數字必須基于上述映射的方法,反向映射回字母(可能有多種方法)
// 例如,"11106" 可以映射為:"AAJF"、"KJF"
// 注意,消息不能分組為(1 11 06),因為 "06" 不能映射為 "F"
// 這是由于 "6" 和 "06" 在映射中并不等價
// 給你一個只含數字的 非空 字符串 s ,請計算并返回 解碼 方法的 總數
// 題目數據保證答案肯定是一個 32位 的整數
// 測試鏈接 : https://leetcode.cn/problems/decode-ways/
public class Code03_DecodeWays {// 暴力嘗試public static int numDecodings1(String s) {return f1(s.toCharArray(), 0);}// s : 數字字符串 // s[i....]有多少種有效的轉化方案public static int f1(char[] s, int i) {if (i == s.length) {return 1;}int ans;if (s[i] == '0') {ans = 0;} else {ans = f1(s, i + 1);if (i + 1 < s.length && ((s[i] - '0') * 10 + s[i + 1] - '0') <= 26) {ans += f1(s, i + 2);}}return ans;}// 暴力嘗試改記憶化搜索public static int numDecodings2(String s) {int[] dp = new int[s.length()];Arrays.fill(dp, -1);return f2(s.toCharArray(), 0, dp);}public static int f2(char[] s, int i, int[] dp) {if (i == s.length) {return 1;}if (dp[i] != -1) {return dp[i];}int ans;if (s[i] == '0') {ans = 0;} else {ans = f2(s, i + 1, dp);if (i + 1 < s.length && ((s[i] - '0') * 10 + s[i + 1] - '0') <= 26) {ans += f2(s, i + 2, dp);}}dp[i] = ans;return ans;}// 嚴格位置依賴的動態規劃public static int numDecodings3(String str) {char[] s = str.toCharArray();int n = s.length;int[] dp = new int[n + 1];dp[n] = 1;for (int i = n - 1; i >= 0; i--) {if (s[i] == '0') {dp[i] = 0;} else {dp[i] = dp[i + 1];if (i + 1 < s.length && ((s[i] - '0') * 10 + s[i + 1] - '0') <= 26) {dp[i] += dp[i + 2];}}}return dp[0];}// 嚴格位置依賴的動態規劃 + 空間壓縮public static int numDecodings4(String s) {// dp[i+1]int next = 1;// dp[i+2]int nextNext = 0;for (int i = s.length() - 1, cur; i >= 0; i--) {if (s.charAt(i) == '0') {cur = 0;} else {cur = next;if (i + 1 < s.length() && ((s.charAt(i) - '0') * 10 + s.charAt(i + 1) - '0') <= 26) {cur += nextNext;}}nextNext = next;next = cur;}return next;}}
code4 639解碼方法 II
// 解碼方法 II
// 一條包含字母 A-Z 的消息通過以下的方式進行了 編碼 :
// ‘A’ -> “1”
// ‘B’ -> “2”
// …
// ‘Z’ -> “26”
// 要 解碼 一條已編碼的消息,所有的數字都必須分組
// 然后按原來的編碼方案反向映射回字母(可能存在多種方式)
// 例如,“11106” 可以映射為:“AAJF”、“KJF”
// 注意,像 (1 11 06) 這樣的分組是無效的,“06"不可以映射為’F’
// 除了上面描述的數字字母映射方案,編碼消息中可能包含 '’ 字符
// 可以表示從 ‘1’ 到 ‘9’ 的任一數字(不包括 ‘0’)
// 例如,"1” 可以表示 “11”、“12”、“13”、“14”、“15”、“16”、“17”、“18” 或 “19”
// 對 “1*” 進行解碼,相當于解碼該字符串可以表示的任何編碼消息
// 給你一個字符串 s ,由數字和 ‘*’ 字符組成,返回 解碼 該字符串的方法 數目
// 由于答案數目可能非常大,返回10^9 + 7的模
// 測試鏈接 : https://leetcode.cn/problems/decode-ways-ii/
dp[i]:以i開始的[i…]的解碼方法個數
=0,s[i]= =‘0’
=dp[i+1]x9,s[i]==‘*’
+=dp[i+2],s[i] s[i+1]構成合法解碼
f1 遞歸
f2 記憶化搜索
package class066;import java.util.Arrays;// 解碼方法 II
// 一條包含字母 A-Z 的消息通過以下的方式進行了 編碼 :
// 'A' -> "1"
// 'B' -> "2"
// ...
// 'Z' -> "26"
// 要 解碼 一條已編碼的消息,所有的數字都必須分組
// 然后按原來的編碼方案反向映射回字母(可能存在多種方式)
// 例如,"11106" 可以映射為:"AAJF"、"KJF"
// 注意,像 (1 11 06) 這樣的分組是無效的,"06"不可以映射為'F'
// 除了上面描述的數字字母映射方案,編碼消息中可能包含 '*' 字符
// 可以表示從 '1' 到 '9' 的任一數字(不包括 '0')
// 例如,"1*" 可以表示 "11"、"12"、"13"、"14"、"15"、"16"、"17"、"18" 或 "19"
// 對 "1*" 進行解碼,相當于解碼該字符串可以表示的任何編碼消息
// 給你一個字符串 s ,由數字和 '*' 字符組成,返回 解碼 該字符串的方法 數目
// 由于答案數目可能非常大,返回10^9 + 7的模
// 測試鏈接 : https://leetcode.cn/problems/decode-ways-ii/
public class Code04_DecodeWaysII {// 沒有取模邏輯// 最自然的暴力嘗試public static int numDecodings1(String str) {return f1(str.toCharArray(), 0);}// s[i....] 有多少種有效轉化public static int f1(char[] s, int i) {if (i == s.length) {return 1;}if (s[i] == '0') {return 0;}// s[i] != '0'// 2) i想單獨轉int ans = f1(s, i + 1) * (s[i] == '*' ? 9 : 1);// 3) i i+1 一起轉化 <= 26if (i + 1 < s.length) {// 有i+1位置if (s[i] != '*') {if (s[i + 1] != '*') {// num num// i i+1if ((s[i] - '0') * 10 + s[i + 1] - '0' <= 26) {ans += f1(s, i + 2);}} else {// num *// i i+1if (s[i] == '1') {ans += f1(s, i + 2) * 9;}if (s[i] == '2') {ans += f1(s, i + 2) * 6;}}} else {if (s[i + 1] != '*') {// * num// i i+1if (s[i + 1] <= '6') {ans += f1(s, i + 2) * 2;} else {ans += f1(s, i + 2);}} else {// * *// i i+1// 11 12 ... 19 21 22 ... 26 -> 一共15種可能// 沒有10、20,因為*只能變1~9,并不包括0ans += f1(s, i + 2) * 15;}}}return ans;}public static long mod = 1000000007;public static int numDecodings2(String str) {char[] s = str.toCharArray();long[] dp = new long[s.length];Arrays.fill(dp, -1);return (int) f2(s, 0, dp);}public static long f2(char[] s, int i, long[] dp) {if (i == s.length) {return 1;}if (s[i] == '0') {return 0;}if (dp[i] != -1) {return dp[i];}long ans = f2(s, i + 1, dp) * (s[i] == '*' ? 9 : 1);if (i + 1 < s.length) {if (s[i] != '*') {if (s[i + 1] != '*') {if ((s[i] - '0') * 10 + s[i + 1] - '0' <= 26) {ans += f2(s, i + 2, dp);}} else {if (s[i] == '1') {ans += f2(s, i + 2, dp) * 9;}if (s[i] == '2') {ans += f2(s, i + 2, dp) * 6;}}} else {if (s[i + 1] != '*') {if (s[i + 1] <= '6') {ans += f2(s, i + 2, dp) * 2;} else {ans += f2(s, i + 2, dp);}} else {ans += f2(s, i + 2, dp) * 15;}}}ans %= mod;dp[i] = ans;return ans;}public static int numDecodings3(String str) {char[] s = str.toCharArray();int n = s.length;long[] dp = new long[n + 1];dp[n] = 1;for (int i = n - 1; i >= 0; i--) {if (s[i] != '0') {dp[i] = (s[i] == '*' ? 9 : 1) * dp[i + 1];if (i + 1 < n) {if (s[i] != '*') {if (s[i + 1] != '*') {if ((s[i] - '0') * 10 + s[i + 1] - '0' <= 26) {dp[i] += dp[i + 2];}} else {if (s[i] == '1') {dp[i] += dp[i + 2] * 9;}if (s[i] == '2') {dp[i] += dp[i + 2] * 6;}}} else {if (s[i + 1] != '*') {if (s[i + 1] <= '6') {dp[i] += dp[i + 2] * 2;} else {dp[i] += dp[i + 2];}} else {dp[i] += dp[i + 2] * 15;}}}dp[i] %= mod;}}return (int) dp[0];}public static int numDecodings4(String str) {char[] s = str.toCharArray();int n = s.length;long cur = 0, next = 1, nextNext = 0;for (int i = n - 1; i >= 0; i--) {if (s[i] != '0') {cur = (s[i] == '*' ? 9 : 1) * next;if (i + 1 < n) {if (s[i] != '*') {if (s[i + 1] != '*') {if ((s[i] - '0') * 10 + s[i + 1] - '0' <= 26) {cur += nextNext;}} else {if (s[i] == '1') {cur += nextNext * 9;}if (s[i] == '2') {cur += nextNext * 6;}}} else {if (s[i + 1] != '*') {if (s[i + 1] <= '6') {cur += nextNext * 2;} else {cur += nextNext;}} else {cur += nextNext * 15;}}}cur %= mod;}nextNext = next;next = cur;cur = 0;}return (int) next;}}
code5 264. 丑數 II
// 丑數 II
// 給你一個整數 n ,請你找出并返回第 n 個 丑數
// 丑數 就是只包含質因數 2、3 或 5 的正整數
// 測試鏈接 : https://leetcode.cn/problems/ugly-number-ii/
dp[i]:保存數據
[i2]:x2的指針
[i3]:x3的指針
[i5]:x5的指針
f0 就是現有子集 *2 *3 *5運算得到后續結果
f1 動態規劃
package class066;// 丑數 II
// 給你一個整數 n ,請你找出并返回第 n 個 丑數
// 丑數 就是只包含質因數 2、3 或 5 的正整數
// 測試鏈接 : https://leetcode.cn/problems/ugly-number-ii/
public class Code05_UglyNumberII {// 時間復雜度O(n),n代表第n個丑數public static int nthUglyNumber(int n) {// dp 0 1 2 ... n// 1 2 ... ?int[] dp = new int[n + 1];dp[1] = 1;for (int i = 2, i2 = 1, i3 = 1, i5 = 1, a, b, c, cur; i <= n; i++) {a = dp[i2] * 2;b = dp[i3] * 3;c = dp[i5] * 5;cur = Math.min(Math.min(a, b), c);if (cur == a) {i2++;}if (cur == b) {i3++;}if (cur == c) {i5++;}dp[i] = cur;}return dp[n];}}
code6 32. 最長有效括號
// 最長有效括號
// 給你一個只包含 ‘(’ 和 ‘)’ 的字符串
// 找出最長有效(格式正確且連續)括號子串的長度。
// 測試鏈接 : https://leetcode.cn/problems/longest-valid-parentheses/
dp[i]:以s[i]結尾構成的最長有效括號的長度
=0,s[i]= =‘(’
=dp[p-1]+dp[i-1]+2 s[p]= =‘(’&&s[i]==‘)’
p=i-dp[i-1]-1
f 動態規劃
package class066;// 最長有效括號
// 給你一個只包含 '(' 和 ')' 的字符串
// 找出最長有效(格式正確且連續)括號子串的長度。
// 測試鏈接 : https://leetcode.cn/problems/longest-valid-parentheses/
public class Code06_LongestValidParentheses {// 時間復雜度O(n),n是str字符串的長度public static int longestValidParentheses(String str) {char[] s = str.toCharArray();// dp[0...n-1]// dp[i] : 子串必須以i位置的字符結尾的情況下,往左整體有效的最大長度int[] dp = new int[s.length];int ans = 0;for (int i = 1, p; i < s.length; i++) {if (s[i] == ')') {p = i - dp[i - 1] - 1;// ? )// p iif (p >= 0 && s[p] == '(') {dp[i] = dp[i - 1] + 2 + (p - 1 >= 0 ? dp[p - 1] : 0);}}ans = Math.max(ans, dp[i]);}return ans;}}
code7 67. 環繞字符串中唯一的子字符串
// 環繞字符串中唯一的子字符串
// 定義字符串 base 為一個 “abcdefghijklmnopqrstuvwxyz” 無限環繞的字符串
// 所以 base 看起來是這樣的:
// “…zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd…”
// 給你一個字符串 s ,請你統計并返回 s 中有多少 不同非空子串 也在 base 中出現
// 測試鏈接 : https://leetcode.cn/problems/unique-substrings-in-wraparound-string/
dp[?] 以?結尾的子字符串的長度,?26個字母
ans=∑dp(0<=i<26)
f 動態規劃
package class066;// 環繞字符串中唯一的子字符串
// 定義字符串 base 為一個 "abcdefghijklmnopqrstuvwxyz" 無限環繞的字符串
// 所以 base 看起來是這樣的:
// "..zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd.."
// 給你一個字符串 s ,請你統計并返回 s 中有多少 不同非空子串 也在 base 中出現
// 測試鏈接 : https://leetcode.cn/problems/unique-substrings-in-wraparound-string/
public class Code07_UniqueSubstringsWraparoundString {// 時間復雜度O(n),n是字符串s的長度,字符串base長度為正無窮public static int findSubstringInWraproundString(String str) {int n = str.length();int[] s = new int[n];// abcde...z -> 0, 1, 2, 3, 4....25for (int i = 0; i < n; i++) {s[i] = str.charAt(i) - 'a';}// dp[0] : s中必須以'a'的子串,最大延伸長度是多少,延伸一定要跟據base串的規則int[] dp = new int[26];// s : c d e....// 2 3 4dp[s[0]] = 1;for (int i = 1, cur, pre, len = 1; i < n; i++) {cur = s[i];pre = s[i - 1];// pre curif ((pre == 25 && cur == 0) || pre + 1 == cur) {// (前一個字符是'z' && 當前字符是'a') || 前一個字符比當前字符的ascii碼少1len++;} else {len = 1;}dp[cur] = Math.max(dp[cur], len);}int ans = 0;for (int i = 0; i < 26; i++) {ans += dp[i];}return ans;}}
code8 940. 不同的子序列 II
// 不同的子序列 II
// 給定一個字符串 s,計算 s 的 不同非空子序列 的個數
// 因為結果可能很大,所以返回答案需要對 10^9 + 7 取余
// 字符串的 子序列 是經由原字符串刪除一些(也可能不刪除)
// 字符但不改變剩余字符相對位置的一個新字符串
// 例如,“ace” 是 “abcde” 的一個子序列,但 “aec” 不是
// 測試鏈接 : https://leetcode.cn/problems/distinct-subsequences-ii/
f 動態規劃
package class066;// 不同的子序列 II
// 給定一個字符串 s,計算 s 的 不同非空子序列 的個數
// 因為結果可能很大,所以返回答案需要對 10^9 + 7 取余
// 字符串的 子序列 是經由原字符串刪除一些(也可能不刪除)
// 字符但不改變剩余字符相對位置的一個新字符串
// 例如,"ace" 是 "abcde" 的一個子序列,但 "aec" 不是
// 測試鏈接 : https://leetcode.cn/problems/distinct-subsequences-ii/
public class Code08_DistinctSubsequencesII {// 時間復雜度O(n),n是字符串s的長度public static int distinctSubseqII(String s) {int mod = 1000000007;char[] str = s.toCharArray();int[] cnt = new int[26];int all = 1, newAdd;for (char x : str) {newAdd = (all - cnt[x - 'a'] + mod) % mod;cnt[x - 'a'] = (cnt[x - 'a'] + newAdd) % mod;all = (all + newAdd) % mod;}return (all - 1 + mod) % mod;}}