【leetcode】491. Increasing Subsequences

题目如下:

解题思路:这题把我折腾了很久,一直没找到很合适的方法,主要是因为有重复的数字导致结果会有重复。最后尝试用字典记录满足条件的序列,保证不重复,居然Accept了。

代码如下:

class Solution(object):
    def findSubsequences(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        queue = []
        dic = {}
        for i in range(len(nums)):
            #pair = Pair([nums[i]], [i])
            queue.append(([nums[i]], i))
        # print queue

        dic = {}

        while len(queue) > 0:
            nl,inx = queue.pop(0)
            if len(nl) > 1:
                s = ''
                for i in nl:
                    s += str(i)
                    s += ','
                s = s[:-1]
                if s not in dic:
                    dic[s] = 1
                #res.append(s)
            for i in range(inx+1,len(nums)):
                if nl[-1] <= nums[i]:
                    queue.append((nl + [nums[i]], i))
        for i in dic.iterkeys():
            rl = i.split(',')
            rl2 = []
            for i in rl:
                rl2.append(int(i))
            res.append(rl2)
        return (res)

猜你喜欢

转载自www.cnblogs.com/seyjs/p/9013884.html