一、題目
Given a sequence of integers, find the longest increasing subsequence (LIS).
You code should return the length of the LIS.
Example For [5, 4, 1, 2, 3], the LIS is [1, 2, 3], return 3
For [4, 2, 4, 5, 3, 7], the LIS is [4, 4, 5, 7], return 4
二、解題思路
方案一:動(dòng)態(tài)規(guī)劃 時(shí)間復(fù)雜度O(n*n)
dp[i] 表示以i結(jié)尾的子序列中LIS的長度。然后我用 dpj 來表示在i之前的LIS的長度。然后我們可以看到,只有當(dāng) a[i]>a[j] 的時(shí)候,我們需要進(jìn)行判斷,是否將a[i]加入到dp[j]當(dāng)中。為了保證我們每次加入都是得到一個(gè)最優(yōu)的LIS,有兩點(diǎn)需要注意:第一,每一次,a[i]都應(yīng)當(dāng)加入最大的那個(gè)dp[j],保證局部性質(zhì)最優(yōu),也就是我們需要找到 max(dpj) ;第二,每一次加入之后,我們都應(yīng)當(dāng)更新dp[j]的值,顯然, dp[i]=dp[j]+1 。 如果寫成遞推公式,我們可以得到 dp[i]=max(dpj)+(a[i]>a[j]?1:0) 。
三、解題代碼
public int longestIncreasingSubsequence(int[] nums) {
int[] f = new int[nums.length];
int max = 0;
for (int i = 0; i < nums.length; i++) {
f[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
f[i] = f[i] > f[j] + 1 ? f[i] : f[j] + 1;
}
}
if (f[i] > max) {
max = f[i];
}
}
return max;
}