# LeetCode 300. Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 

Note:

• There may be more than one LIS combination, it is only necessary for you to return the length.
• Your algorithm should run in O(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

dp解：递推式：dp[i] = max(dp[j]) for (j < i && nums[j] < nums[i]) + 1，最后注意返回的是dp数组里最大的而不是最后一个。以及一些int variable设成0或者1或者-1也有讲究，具体看代码注释。

Runtime: 9 ms, faster than 73.39% of Java online submissions for Longest Increasing Subsequence.

Memory Usage: 37.1 MB, less than 96.47% of Java online submissions for Longest Increasing Subsequence.

class Solution {
public int lengthOfLIS(int[] nums) {
if (nums.length == 0) {
return 0;
}
int[] dp = new int[nums.length];
dp[0] = 1;
int result = 1;  // if assigning as 0, it will return 0 for 1 element array
for (int i = 1; i < nums.length; i++) {
int max = 0;  // assigning as 0 can simplify the dp[i] = max + 1
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
max = Math.max(max, dp[j]);
}
}
dp[i] = max + 1;
result = Math.max(result, dp[i]);
}
// attention! not returning the last element, it's returning the largest
return result;
}
}

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

wenyq7

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
05-31 1065
05-27 3万+

09-03 6708
03-11 3571
09-11
08-06 6400
08-01 11万+
03-11 2255
03-14 7346
07-25 5007
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客