最长递增序列
题目描述: 给定数组arr,设长度为n,输出arr的最长递增子序列。(如果有多个答案,请输出其中字典序最小的)
示例1
输入
[2,1,5,3,6,4,8,9,7]
返回值
[1,3,4,8,9]
示例2
输入
[1,2,8,6,4]
返回值
[1,2,4]
说明: 其最长递增子序列有3个,(1,2,8)、(1,2,6)、(1,2,4)其中第三个字典序最小,故答案为(1,2,4)
#
# retrun the longest increasing subsequence
# @param arr int整型一维数组 the array
# @return int整型一维数组
#运行超时
import itertools
class Solution:
def LIS(self , arr ):
# write code here
flag=0
#new_arr=[]
#count=sum([i for i in range(len(arr))])
#print(count)
for i in range(len(arr),0,-1):
#print('--')
#print(i)
for j in itertools.combinations(arr,i):
#print(j)
if list(j)==sorted(j):
flag=1
#num = sum([arr.index(x) for x in list(j)]
#count=num
new_arr=list(j)
if flag==1:
break
return new_arr
sol=Solution()
sol.LIS([1,2,8,6,4])
#
# retrun the longest increasing subsequence
# @param arr int整型一维数组 the array
# @return int整型一维数组
#
import bisect
class Solution:
def LIS(self , arr ):
# write code here
n = len(arr)
dp = [1] * n
lenth = 1
array = [arr[0]]
for i in range(1, n):
if arr[i] > array[-1]:
lenth += 1
dp[i] = lenth
array.append(arr[i])
else:
index = bisect.bisect(array, arr[i])
dp[i] = index + 1
array[index] = arr[i]
res = []
max_num = array[-1]
max_num_index = arr.index(max_num)
lenth = max(dp)
for i in range(max_num_index, -1, -1):
if res == [] or (arr[i] < res[-1] and dp[i] == lenth):
res.append(arr[i])
lenth -= 1
return res[::-1]
sol=Solution()
sol.LIS([1,2,8,6,4])
补充:
import itertools
[i for i in itertools.permutations([2,1,5,3],2)]#无序不放回抽样
import itertools
[i for i in itertools.combinations([2,1,5,3],2)]#顺序不放回抽样