动态规划解最长递增子序列(O(n^2))
核心
- 状态的定义:设dp[k]为到k项为止,最长递增子序列的长度;
- 状态方程的定义:dp[k] = max(dp[k], dp[i] + 1) | i < k && arr[i] < arr[k],需遍历前面所有项
Code
#include <iostream>
#include <vector>
#define MAX(m, n) (m > n ? m : n)
namespace {
using std::cin;
using std::cout;
using std::endl;
using std::vector;
}
int main(int argc, const char *argv[])
{
int i, j;
int dp[7] = { 0 };
int arr[6] = { 1, 7, 2, 8, 3, 4 };
for (i = 0; i < 7; ++i) {
dp[i] = 1;
}
for (i = 1; i < 6; ++i) {
for (j = 0; j < i; ++j) {
if (arr[j] < arr[i]) {
dp[i] = MAX(dp[i], dp[j] + 1);
}
}
}
cout << dp[5] << endl;
return 0;
}