# Longest Increasing Subsequence
- tags: [[DP_Sequence](# "单序列动态规划,通常使用 f[i] 表示前i个位置/数字/字母... 使用 f[n-1] 表示最后返回结果。")]
### Source
- lintcode: [(76) Longest Increasing Subsequence](http://www.lintcode.com/en/problem/longest-increasing-subsequence/)
- [Dynamic Programming | Set 3 (Longest Increasing Subsequence) - GeeksforGeeks](http://www.geeksforgeeks.org/dynamic-programming-set-3-longest-increasing-subsequence/)
### Problem
Given a sequence of integers, find the longest increasing subsequence (LIS).
You code should return the length of the LIS.
#### 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 [4, 4, 5, 7], return 4
#### Challenge
Time complexity O(n^2) or O(nlogn)
#### 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_common_subsequence_problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem)
### 题解
由题意知这种题应该是单序列动态规划题,结合四要素,可定义`f[i]`为前`i`个数字中的 LIC 数目,那么问题来了,接下来的状态转移方程如何写?似乎写不出来... 再仔细看看 LIS 的定义,状态转移的关键一环应该为数字本身而不是最后返回的结果(数目),那么理所当然的,我们应定义`f[i]`为前`i`个数字中以第`i`个数字结尾的 LIS 长度,相应的状态转移方程为`f[i] = {1 + max{f[j]} where j < i, nums[j] < nums[i]}`, 该转移方程的含义为在所有满足以上条件的 j 中将最大的`f[j]` 赋予`f[i]`, 如果上式不满足,则`f[i] = 1`. 具体实现时不能直接使用`f[i] = 1 + max(f[j])`, 应为若`if f[i] < 1 + f[j], f[i] = 1 + f[j]`. 最后返回 `max(f[])`.
### Python
~~~
class Solution:
"""
@param nums: The integer array
@return: The length of LIS (longest increasing subsequence)
"""
def longestIncreasingSubsequence(self, nums):
if not nums:
return 0
lis = [1] * len(nums)
for i in xrange(1, len(nums)):
for j in xrange(i):
if nums[j] <= nums[i] and lis[i] < 1 + lis[j]:
lis[i] = 1 + lis[j]
return max(lis)
~~~
### C++
~~~
class Solution {
public:
/**
* @param nums: The integer array
* @return: The length of LIS (longest increasing subsequence)
*/
int longestIncreasingSubsequence(vector<int> nums) {
if (nums.empty()) return 0;
int len = nums.size();
vector<int> lis(len, 1);
for (int i = 1; i < len; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[j] <= nums[i] && (lis[i] < lis[j] + 1)) {
lis[i] = 1 + lis[j];
}
}
}
return *max_element(lis.begin(), lis.end());
}
};
~~~
### Java
~~~
public class Solution {
/**
* @param nums: The integer array
* @return: The length of LIS (longest increasing subsequence)
*/
public int longestIncreasingSubsequence(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int[] lis = new int[nums.length];
Arrays.fill(lis, 1);
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] <= nums[i] && (lis[i] < lis[j] + 1)) {
lis[i] = lis[j] + 1;
}
}
}
// get the max lis
int max_lis = 0;
for (int i = 0; i < lis.length; i++) {
if (lis[i] > max_lis) {
max_lis = lis[i];
}
}
return max_lis;
}
}
~~~
### 源码分析
1. 初始化数组,初始值为1
1. 根据状态转移方程递推求得`lis[i]`
1. 遍历`lis` 数组求得最大值
### 复杂度分析
使用了与 nums 等长的空间,空间复杂度 O(n)O(n)O(n). 两重 for 循环,最坏情况下 O(n2)O(n^2)O(n2), 遍历求得最大值,时间复杂度为 O(n)O(n)O(n), 故总的时间复杂度为 O(n2)O(n^2)O(n2).
# Follow up
上述问题均只输出最大值,现在需要输出 LIS 中的每一个原始元素值。
### 题解1 - LIS
由于以上递归推导式只能返回最大值,如果现在需要返回 LIS 中的每个元素,直观来讲,构成 LIS 数组中的值对应的原数组值即为我们想要的结果。我们不妨从后往前考虑,依次移除 lis[i] 数组中的值(减一)和索引,遇到和 lis[i]的值相等的 LIS 时即加入到最终返回结果。
### Java
~~~
import java.util.*;
public class Solution {
/**
* @param nums: The integer array
* @return: LIS array
*/
public int[] longestIncreasingSubsequence(int[] nums) {
if (nums == null || nums.length == 0) return null;
int[] lis = new int[nums.length];
Arrays.fill(lis, 1);
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] <= nums[i] && (lis[i] < lis[j] + 1)) {
lis[i] = lis[j] + 1;
}
}
}
// get the max lis
int max_lis = 0, index = 0;
for (int i = 0; i < lis.length; i++) {
if (lis[i] > max_lis) {
max_lis = lis[i];
index = i;
}
}
// get result
int[] result = new int[max_lis];
for (int i = index; i >= 0; i--) {
if (lis[i] == max_lis) {
result[max_lis - 1] = nums[i];
max_lis--;
}
}
return result;
}
public static void main(String[] args) {
int[] nums = new int[]{5, 4, 1, 2, 3};
Solution sol = new Solution();
int[] result = sol.longestIncreasingSubsequence(nums);
for (int i : result) {
System.out.println(i);
}
}
}
~~~
关于`// get result` 那一节中为何`max_lis` 自减一定是会得到最终想要的结果?假如有和其一样的lis如何破?根据 DP 中状态的定义可知正好为其逆过程,只不过答案不唯一,反向输出的答案输出的是最靠右的结果。
- Preface
- Part I - Basics
- Basics Data Structure
- String
- Linked List
- Binary Tree
- Huffman Compression
- Queue
- Heap
- Stack
- Set
- Map
- Graph
- Basics Sorting
- Bubble Sort
- Selection Sort
- Insertion Sort
- Merge Sort
- Quick Sort
- Heap Sort
- Bucket Sort
- Counting Sort
- Radix Sort
- Basics Algorithm
- Divide and Conquer
- Binary Search
- Math
- Greatest Common Divisor
- Prime
- Knapsack
- Probability
- Shuffle
- Basics Misc
- Bit Manipulation
- Part II - Coding
- String
- strStr
- Two Strings Are Anagrams
- Compare Strings
- Anagrams
- Longest Common Substring
- Rotate String
- Reverse Words in a String
- Valid Palindrome
- Longest Palindromic Substring
- Space Replacement
- Wildcard Matching
- Length of Last Word
- Count and Say
- Integer Array
- Remove Element
- Zero Sum Subarray
- Subarray Sum K
- Subarray Sum Closest
- Recover Rotated Sorted Array
- Product of Array Exclude Itself
- Partition Array
- First Missing Positive
- 2 Sum
- 3 Sum
- 3 Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Merge Sorted Array
- Merge Sorted Array II
- Median
- Partition Array by Odd and Even
- Kth Largest Element
- Binary Search
- Binary Search
- Search Insert Position
- Search for a Range
- First Bad Version
- Search a 2D Matrix
- Search a 2D Matrix II
- Find Peak Element
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array II
- Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array II
- Median of two Sorted Arrays
- Sqrt x
- Wood Cut
- Math and Bit Manipulation
- Single Number
- Single Number II
- Single Number III
- O1 Check Power of 2
- Convert Integer A to Integer B
- Factorial Trailing Zeroes
- Unique Binary Search Trees
- Update Bits
- Fast Power
- Hash Function
- Count 1 in Binary
- Fibonacci
- A plus B Problem
- Print Numbers by Recursion
- Majority Number
- Majority Number II
- Majority Number III
- Digit Counts
- Ugly Number
- Plus One
- Linked List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List II
- Remove Duplicates from Unsorted List
- Partition List
- Two Lists Sum
- Two Lists Sum Advanced
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle II
- Reverse Linked List
- Reverse Linked List II
- Merge Two Sorted Lists
- Merge k Sorted Lists
- Reorder List
- Copy List with Random Pointer
- Sort List
- Insertion Sort List
- Check if a singly linked list is palindrome
- Delete Node in the Middle of Singly Linked List
- Rotate List
- Swap Nodes in Pairs
- Remove Linked List Elements
- Binary Tree
- Binary Tree Preorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Maximum Depth of Binary Tree
- Balanced Binary Tree
- Binary Tree Maximum Path Sum
- Lowest Common Ancestor
- Invert Binary Tree
- Diameter of a Binary Tree
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- Subtree
- Binary Tree Zigzag Level Order Traversal
- Binary Tree Serialization
- Binary Search Tree
- Insert Node in a Binary Search Tree
- Validate Binary Search Tree
- Search Range in Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Binary Search Tree Iterator
- Exhaustive Search
- Subsets
- Unique Subsets
- Permutations
- Unique Permutations
- Next Permutation
- Previous Permuation
- Unique Binary Search Trees II
- Permutation Index
- Permutation Index II
- Permutation Sequence
- Palindrome Partitioning
- Combinations
- Combination Sum
- Combination Sum II
- Minimum Depth of Binary Tree
- Word Search
- Dynamic Programming
- Triangle
- Backpack
- Backpack II
- Minimum Path Sum
- Unique Paths
- Unique Paths II
- Climbing Stairs
- Jump Game
- Word Break
- Longest Increasing Subsequence
- Palindrome Partitioning II
- Longest Common Subsequence
- Edit Distance
- Jump Game II
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Distinct Subsequences
- Interleaving String
- Maximum Subarray
- Maximum Subarray II
- Longest Increasing Continuous subsequence
- Longest Increasing Continuous subsequence II
- Graph
- Find the Connected Component in the Undirected Graph
- Route Between Two Nodes in Graph
- Topological Sorting
- Word Ladder
- Bipartial Graph Part I
- Data Structure
- Implement Queue by Two Stacks
- Min Stack
- Sliding Window Maximum
- Longest Words
- Heapify
- Problem Misc
- Nuts and Bolts Problem
- String to Integer
- Insert Interval
- Merge Intervals
- Minimum Subarray
- Matrix Zigzag Traversal
- Valid Sudoku
- Add Binary
- Reverse Integer
- Gray Code
- Find the Missing Number
- Minimum Window Substring
- Continuous Subarray Sum
- Continuous Subarray Sum II
- Longest Consecutive Sequence
- Part III - Contest
- Google APAC
- APAC 2015 Round B
- Problem A. Password Attacker
- Microsoft
- Microsoft 2015 April
- Problem A. Magic Box
- Problem B. Professor Q's Software
- Problem C. Islands Travel
- Problem D. Recruitment
- Microsoft 2015 April 2
- Problem A. Lucky Substrings
- Problem B. Numeric Keypad
- Problem C. Spring Outing
- Microsoft 2015 September 2
- Problem A. Farthest Point
- Appendix I Interview and Resume
- Interview
- Resume