My code:
public class Solution {
public int numDistinct(String s, String t) {
if (s == null || t == null) {
return 0;
}
else if (s.length() == 0) {
return 0;
}
else if (t.length() == 0) {
return s.length();
}
int m = s.length();
int n = t.length();
int[][] dp = new int[m][n];
int counter = 0;
char target = t.charAt(0);
for (int i = 0; i < m; i++) {
char curr = s.charAt(i);
if (curr == target) {
counter++;
}
dp[i][0] = counter;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = dp[i - 1][j];
if (s.charAt(i) == t.charAt(j)) {
dp[i][j] += dp[i - 1][j - 1];
}
}
}
return dp[m - 1][n - 1];
}
}
真的沒想到這道題目我可以自己做出來。。。還是很興奮的。
iteration DP
dp[i][j] 表示, s[0, i] 與 t[0, j] 的 distinct subsequences
那么遞推式是什么呢?
假設給了我們這兩個string
s[0, i] 與 t[0, j]
那么,
dp[i][j] = dp[i - 1][j];
if (t[j] == s[i]) {
dp[i][j] += dp[i - 1][j - 1];
}
即, dp[i][j] 至少等于 dp[i - 1][j]
如果 s[i] == t[j]
那么,還要看 s[0, i - 1] 與 t[0, j - 1] 的匹配狀態,
即, dp[i][j] += dp[i - 1][j - 1]
這么一看,思路好像很簡單。
這就是DP吧。其實我一開始思路也沒有直接就這么簡潔。
提交了幾次,失敗后,再看代碼邏輯,逐漸改出來的。
初始狀態是什么?
dp[i][0], 看 s[0, i] 里面有多少個字母 == t[0]
dp[0][j] = 0, j > 0
差不多就這樣了吧。
然后我發現DP做到現在大致分為四類題目。
第一種的典型題目是
burst ballon
給你一個數組,你需要 divide and conquer, 將數組整體劈成兩個獨立的個體,分別計算,再統計結果。中間加上cache以加快速度。
from top to bottom
也可以用iteration DP來做,但很難想到。
edit distance
兩個string,完全可以用 dp[][] 來解決。這道題目也是這個類型。
不是劈開。而是從無到有,從底到頂
from bottom to top
house robbing, best time to buy and sell stock with cooldown
狀態機, state machine. 畫出 狀態機,然后照著寫出dp遞歸式,就差不多了。
perfect square, climbing stair, Integer Break
這些都是生成一個數組, nums[n]
然后, nums[i] 與 nums[0, i - 1] 有關。
比如, perfect square, nums[i] 可能 =
nums[1] + nums[i - 1]
nums[2] + nums[i - 2]
nums[3] + nums[i - 3]
...
然后采用某種策略,省去一些多余的例子。
Integer break 也是如此。
這只是我的一種感覺,理論上肯定有很多不足。但對解決DP題目還是會有一定幫助的。就像看到時間要求如果有含 log n 項, 那么,就一定存在 binary search 這樣的東西。
Anyway, Good luck, Richardo! -- 08/27/2016