Arrays 如何改进递增子序列算法以合并未排序数组?

Arrays 如何改进递增子序列算法以合并未排序数组?,arrays,algorithm,python-3.x,sorting,Arrays,Algorithm,Python 3.x,Sorting,我一直致力于解决越来越多的子序列问题。我提出的算法目前只解决排序数组。我正在用python 3.5编写代码。此问题位于Leetcode上 在递增子序列问题中,给我一个整数数组,任务是找到给定数组中所有不同的可能递增子序列,递增子序列的长度至少应为2 例如: 输入-[4,6,7,7] 输出-[[4,6],[4,7],[4,6,7],[4,6,7,7],[6,7],[6,7,7],[7,7],[4,7,7]] 以下是我解决这个问题的工作代码: array = [4,6,7,7] def incrS

我一直致力于解决越来越多的子序列问题。我提出的算法目前只解决排序数组。我正在用python 3.5编写代码。此问题位于Leetcode上

在递增子序列问题中,给我一个整数数组,任务是找到给定数组中所有不同的可能递增子序列,递增子序列的长度至少应为2

例如:

输入-[4,6,7,7]

输出-[[4,6],[4,7],[4,6,7],[4,6,7,7],[6,7],[6,7,7],[7,7],[4,7,7]]

以下是我解决这个问题的工作代码:

array = [4,6,7,7]

def incrSubseq(array): #Only works for sorted arrays.
    res = [[]]
    ans = []
    for num in array:
        res += [item + [num] for item in res if (item+[num] not in res)]
    for values in res:
        if len(values)>1:
            ans = ans + [values]
    print(ans)
incrSubseq(array)
这段代码是如何工作的

  • 它首先初始化一个结果变量
    res
    (列表列表) 由空列表初始化
  • 然后我迭代给定的整数数组
    array
    ,它是按排序的,将每个元素添加到列表中,从而找到可以形成的所有子集。列表理解中的
    if
    语句过滤掉重复的项,因此只保留列表的一个副本
  • 然后过滤所有长度大于1的数组
  • 因此,解决问题

    现在,我缺少的是一种解决未排序数组的方法。就我的理解而言,我需要在尝试将元素添加到
    res
    时,检查其是否大于或等于前面的项目


    res+=[item+[num]用于res中的item if(item+[num]不在res中)和(item您的想法完全正确!只需检查
    item
    中的最后一个元素是否比前一个元素小(可能允许相等,取决于如何定义)


    因此,您添加了检查
    项[-1],您能否解释一下
    len(项)==0如何改变一切。我没有完全理解短路。而且我的代码没有优化。
    array=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
    将花费大量时间。由于我正在生成所有子集,因此这将是一个指数复杂度的代码。我想是O(n^n)。谢谢您的帮助!:)
    array = [4,6,3,7]
    
    def incrSubseq(array): # Works for sorted arrays too :)
        res = [[]]
    
        for num in array:
            res += [item + [num] for item in res if (item + [num] not in res 
                                                     and (len(item) == 0 or item[-1] <= num))]
    
        return [values for values in res if len(values) > 1]
    
    print(incrSubseq(array))
    
    for num in array:
        for item in res:
            if item + [num] not in res:
                if len(item) == 0:
                    # item is empty.
                    res += [num]
                else:
                    # item is not empty so we check its last element.
                    if item[-1] <= num:
                        res += item + [num]
                    else:
                        # We got something increasing here. Do not add.
                        pass