1、最長上升子序列(Longest increasing subsequence)ios
狀態(最關鍵):f[N]爲動規數組,f[i]表示從第一個字符開始,以a[i]爲最後一個字符的序列的最長遞增子序列的長度。數組
由狀態引出狀態轉移方程,由於f[i]的設定,因此能夠去比較最後一個字符從而更新f[i];spa
例題:POJ2533 Longest Ordered Subsequencecode
AC代碼blog
#include<iostream> #include<algorithm> using namespace std; int main() { int f[1005]; int a[1005]; int n; cin >> n; for (int i = 0; i < n; i++)cin >> a[i]; f[0] = 1; for (int i = 1; i < n; i++) { f[i] = 1; for (int j = 0; j < i; j++) { if (a[j] < a[i])f[i] = max(f[i], f[j] + 1); } } int ans = 1; for (int i = 0; i < n; i++)ans = max(ans, f[i]); cout << ans << endl; return 0; }