---
title: "Longest Increasing Subsequence"
author: "KickCode"
date: "2016-02-28T04:22:24Z"
tags: []
categories: ["编程语言"]
slug: "longest-increasing-subsequence"
draft: false
lastmod: "2016-02-28T04:22:24Z"
id: 2279304
url: "https://kickcode.iteye.com/blog/2279304"
---

Given an unsorted array of integers, find the length of longest increasing subsequence.

For example,
Given ,
The longest increasing subsequence is , therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.

Your algorithm should run in O(n^2) complexity.

用动态规划解决，时间复杂度为O(n^2)。创建一个动态数组dp，维护一个变量max来记录最大长度。dp*代表到nums*元素的最长递增序列，最后返回max。代码如下：

```java

public class Solution {
    public int lengthOfLIS(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int[] result = new int[nums.length];
        Arrays.fill(result, 1);
        int max = 1;
        for(int i = 1; i < result.length; i++) {
            for(int j = i; j > 0; j--) {
                if(nums[i] > nums[j - 1]) {
                    result[i] = Math.max(result[i], result[j - 1] + 1);
                }
            }
            if(result[i] > max) max = result[i];
        }
        return max;
    }
}

```