首页 > 其他 > 详细

[LeetCode] Longest Increasing Subsequence

时间:2015-11-03 22:57:49      阅读:260      评论:0      收藏:0      [点我收藏+]

A typical O(n^2) solution uses dynamic programming. Let‘s use lens[j] to denote the length of the LIS ending with nums[j]. The state equations are

lens[0] = 1

lens[j] = max_{i = 0, 1, 2, ..., j - 1}(lens[j], lens[i] + 1)

Then the length of the LIS of nums is just the maximum value in lens. The code is as follows.

 1 class Solution {
 2 public:
 3     int lengthOfLIS(vector<int>& nums) {
 4         if (nums.empty()) return 0;
 5         int n = nums.size(), ml = 1;
 6         vector<int> lens(n, 1);
 7         for (int j = 1; j < n; j++) {
 8             for (int i = 0; i < j; i++)
 9                 if (nums[j] > nums[i])
10                     lens[j] = max(lens[j], lens[i] + 1);
11             ml = max(ml, lens[j]);
12         }
13         return ml;
14     }
15 };

The O(nlogn) solution will come out soon...

[LeetCode] Longest Increasing Subsequence

原文:http://www.cnblogs.com/jcliBlogger/p/4934562.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!