动态规划(DP)的基本思想是:当前子问题的解可由上一子问题的解得出。
动态规划算法通常基于由一个递推公式(状态转移方程)和若干个初始状态(状态)。
应用
1、LIS(Longest Increasing Subsequence):求一个数组中的最长非降子序列的长度。
子问题
我们可以考虑先求A[0]、A[1]、A[2] ... A[i]的最长非降子序列长度,这个LIS的一个子问题。
接着,我们可以已定义d[i]来表示前i个数中以A[i]结尾的最长非降子序列长度。
当我们求出d[1]~d[n],那么其中最大的数就是所求。
i与i-1的关系
假设已经得到了d[1]~d[i-1],那么d[i]就是前i-1个数中小于等于A[i]的那些数对应的最长非降子序列长度
的最大值。
Code
public class LIS {
public int lis(int[] array) {
// 前i个数的最长非降子序列长度集合
int[] d = new int[array.length];
int result = 0;
d[0] = 1; // 初始状态
// 从第二个数开始遍历
for (int i = 1; i < array.length; i++) {
d[i] = 1; // 默认值
for (int j = 0; j < i; j++) {
// 以array[i]结尾的最长非降子序列长度
if (array[j] <= array[i] && d[j] + 1 > d[i])
d[i] = d[j] + 1;
}
}
// 找出最大长度
for (int k = 0; k < array.length; k++) {
if (d[k] > result)
result = d[k];
}
return result;
}
public static void main(String[] args) {
int[] array = { 5, 3, 4, 8, 6, 7 };
System.out.println("最长非降子序列的长度为" + new LIS().lis(array) + "。");
}
}