DP问题的特征:
- An instance is solved using the solutions for smaller instances.
- The solution for a smaller instance might be needed multiple times.
- The solutions to smaller instances are stored in a table, so that each smaller instance is solved only once.
- Additional space is used to save time.
-----------------------------------------------------------------------
From Leetcode:
1. Edit distance
2. Word Break
3. Longest Palindromic Substring
4. Maximum Subarray
---------------------------------------------------------------------
From Topcoder:
求最:
1, Given a list of N coins, their values (V1, V2, ... , VN), and the total sum S. Find the minimum number of coins the sum of which is S (we can use as many coins of one type as we want), or report -1 if it's not possible to select coins in such a way that they sum up to S.
public int getMin(int[] A, int s) {
if (A == null || A.length == 0) {
return -1;
}
int[] res = new int[s + 1];
for (int i = 1; i < res.length; i++) {
res[i] = Integer.MAX_VALUE;
for (int j = 0; j < A.length; j++) {
if (A[j] <= i) {
int pre = res[i - A[j]];
if (pre < Integer.MAX_VALUE) {
res[i] = Math.min(pre + 1, res[i]);
}
}
}
}
return res[s] < Integer.MAX_VALUE ? res[s] : -1;
}
2, Given a sequence of N numbers A[1] , A[2] , ..., A[N] . Find the length of the longest non-decreasing sequence.
辅助的array存储含有s[i]作为末尾元素的non-decreasing sub-sequence的长度
public static int getLength(int[] s) {
if (s == null || s.length == 0) {
return 0;
}
int max = 0;
int[] lenSeq = new int[s.length];
for (int i = 0; i < lenSeq.length; i++) {
lenSeq[i] = 1;
for (int j = 0; j < i; j++) {
if (s[i] >= s[j]) {
lenSeq[i] = Math.max(lenSeq[i], lenSeq[j] + 1);
max = Math.max(max, lenSeq[i]);
}
}
}
return max;
}
参考:
X WANG: http://www.programcreek.com/2012/11/top-10-algorithms-for-coding-interview/