码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Increasing Subsequence

时间:2016-07-08 01:34:36      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

Given a sequence of integers, find the longest increasing subsequence (LIS).

You code should return the length of the LIS.

Clarification

What‘s the definition of longest increasing subsequence?

  • The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence‘s elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.

  • https://en.wikipedia.org/wiki/Longest_increasing_subsequence

Example
For `[5, 4, 1, 2, 3]`, the LIS is [1, 2, 3], return `3`

For `[4, 2, 4, 5, 3, 7]`, the LIS is `[2, 4, 5, 7]`, return `4`
分析:
用一个数组a记录对于arr[i], 到它那里最长的subsequence是多少,那么对于arr[i + 1],我们需要从0比较到i, 如果arr[j] < arr[i + 1], 并且a[j] > a[i + 1], 我们就更新a[j + 1]的值。
 1 public class Solution {
 2     /**
 3      * @param nums: The integer array
 4      * @return: The length of LIS (longest increasing subsequence)
 5      */
 6     public int longestIncreasingSubsequence(int[] arr) {
 7         // array a is used to store the maximum length
 8         int[] a = new int[arr.length];
 9         // initialization, set all the elements in array a to 1;
10         for (int i = 0; i < a.length; i++) {
11             a[i] = 1;
12         }
13         for (int i = 1; i < arr.length; i++) {
14             for (int j = 0; j < i; j++ ) {
15                 if (arr[i] >= arr[j] && a[i] <= a[j] ) {
16                     a[i] = a[j] + 1;
17                 }
18             }
19         }
20         int max = 0;
21         //find the longest subsequence
22         for (int i = 0; i < a.length; i++) {
23             if (a[i] > max ) max = a[i];
24         }
25         return max;
26     }
27 }

 

Longest Increasing Subsequence

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5652051.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!