300. 最长递增子序列
【题目】给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
【分析1】找到所有递增子序列,然后求最长长度,超时,通过率:22/54;
【分析2】动态规划,
class Solution {LinkedList<LinkedList<Integer> > allLIS = new LinkedList<>();public int lengthOfLIS(int[] nums) {//找到所有递增子序列,然后返回最长的长度LinkedList<Integer> temp = new LinkedList<>();dfs(nums, 0, -10001, temp);int res = 0;for (LinkedList<Integer> lis : allLIS) {res = Math.max(res, lis.size());}return res;}public void dfs(int[] nums, int cur, int preNum, LinkedList<Integer> temp) {if (cur == nums.length) {if (!temp.isEmpty()) {allLIS.add(new LinkedList<>(temp));}return;}if (nums[cur] > preNum) {temp.add(nums[cur]);dfs(nums, cur+1, nums[cur], temp);temp.removeLast();}if (nums[cur] != preNum) {dfs(nums, cur+1, preNum, temp);}}}
class Solution {
public int lengthOfLIS(int[] nums) {
//动态规划思路,dp[i]表示以num[i]这个数结尾的最长递增子序列的长度
int n = nums.length;
int[] dp = new int[n];
for (int i=0; i<n; i++) {
dp[i] = 1;
}
for (int i=0; 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=0; i<n; i++) {
res = Math.max(res, dp[i]);
}
return res;
}
}
