问题:
给定一个无序的整数数组,找到其中最长上升子序列的长度。
示例:
输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
说明:
可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
你算法的时间复杂度应该为 O(n2) 。
思路:
我们可以使用动态规划来进行解答
1,设置dp[]数组:dp[i]表示以第i个数为结尾的最长上升子序列的长度
2,边界条件:dp[0] = 1;
3,进行循环
从1~n-1:循环i,计算dp[i-1]
10 9 2 5 3 7 101 18
0 1 2 3 4 5 6 7
dp[0] = 1;
nums[1] < nums[0] ->dp[1] = 1
nums[2] < nums[1] nums[2] < nums[0] -> dp[2] = 1
nums[3] > nums[2] dp[3] = max(dp[2]+1,dp[3]) = 2
nums[4] > nums[2] dp[4] = max(dp[2]+1,dp[4]) = 2
nums[5]> nums[4] nums[5]>nums[3] nums[5]>nums[2] dp[5] = max(dp[2]+1 dp[3]+1,dp[4]+1,dp[5]) = 3
.................
从0~i-1,循环j,如果num[i] > num[j] 说明num[i] 可以放在nums[j]的后面,组成最长上升子序列
整体的最长上升子序列就为dp[0],dp[1]....dp[n-1]中最大的数
代码:
public class Test300 {
public static void main(String[] args) {
int[] nums = {10,9,2,5,3,7,101,18};
System.out.println(lengthOfLIS(nums));
}
public static int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = 1;
int max = dp[0];
for(int i = 1;i < nums.length;i++) {
dp[i] = 1;
for(int j = 0;j <= i-1;j++) {
if(nums[i] > nums[j] && dp[j]+1 > dp[i]){
dp[i] = dp[j]+1;
}
}
if(max < dp[i]){
max = dp[i];
}
}
return max;
}
}