题目:给定一个无序的整数数组,找到其中最长上升子序列的长度。
例子:
输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
思路:动态规划
- 状态: dp[i]表示以i结尾的子串最长上升序列的长度
- 初始化:Arrays.fill(dp , 1);
- 状态转移方程:dp[i] = Math.max(dp[i] , dp[j] + 1) (if(dp[i] > dp[j]) j = 0 , 1 ,2…, i - 1);
- 结果:dp[]的最大值
class Solution {
public int lengthOfLIS(int[] nums) {
if(nums == null || nums.length ==0){
return 0;
}
int n = nums.length;
int[] dp = new int[n];
Arrays.fill(dp , 1);
for(int i = 1 ; i < n ; i++){
for(int j = 0 ; j < i ; j++){
if(nums[i] > nums[j]){
dp[i] = Math.max(dp[i] , dp[j] + 1);
}
}
}
int res = 0;
for(int i : dp){
res = Math.max(res , i);
}
return res;
}
}