刚开始写,如有错误还望各位看官指出。若有描述不清,也请诸位提点。
导读
通过动态规划使用C语言实现求数组中最大升序(或降序)子序列长度问题。
原题
Longest Increasing Subsequence
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given[10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is[2, 3, 7, 101], therefore the length is4. 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(n2) complexity.
Follow up:Could you improve it to O(nlogn) time complexity?
Credits:
Special thanks to@pbrotherfor adding this problem and creating all test cases.
Subscribeto see which companies asked this question.
翻译:
给出一个无序的整形数组,找出它的最大升序子序列。
举个栗子,
示例数组 arr[] = {10, 9, 2, 5, 3, 7, 101, 18},
数组arr的最长升序子序列是 {2, 3, 7, 101},因此长度是4。
请注意,可能有一个以上的LIS(最长上升子序列)的组合,只需要返回长度就好。
时间复杂度O(n²)前提下实现。
进阶:时间复杂度O(nlogn)前提下实现。
以下不译。
正文
以下为两种时间复杂度的C语言解法,已将log相关代码注释掉了,并粘上分步log,并简要概述思路,共同学习进步。
O(n²)
思路:
定义一个数组lis,记录以目标序列nums[0]开头,以每个元素结尾的子串的最大升序子串长度。
取出li