【LeetCode】491. Increasing Subsequences 解題報告(Python)__Python

來源:互聯網
上載者:User
【LeetCode】491. Increasing Subsequences 解題報告(Python)

標籤(空格分隔): LeetCode

題目地址:https://leetcode.com/problems/increasing-subsequences/description/ 題目描述:

Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2 .

Example:Input: [4, 6, 7, 7]Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]

Note: The length of the given array will not exceed 15. The range of integer in the given array is [-100,100]. The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence. 題目大意

找出一個數組中所有的遞增的序列。 解題方法

我先寫了dfs的做法,結果python代碼逾時了,這個讓我很不爽,畢竟你的related topics寫的就是dfs好麼。。然後參考了網上的dp的做法,成功解決掉了。

dfs做法:

class Solution:    def findSubsequences(self, nums):        """        :type nums: List[int]        :rtype: List[List[int]]        """        res = []        self.dfs(nums, 0, res, [])        return res    def dfs(self, nums, index, res, path):        if len(path) >= 2 and path not in res:            res.append(path.copy())        for i in range(index, len(nums)):            if not path or path[-1] <= nums[i]:                path += [nums[i]]                self.dfs(nums, i + 1, res, path)                path.pop()

下面是動態規劃的代碼,使用了一個set來保證不會有重複,然後由於set之中只能放不可變的對象,所以放進去的是元組對象。當我們遍曆到nums的每個數位時候,對set中的所有的元素進行遍曆,看每個tuple元素的最後一個數字是否是小於等於當前的num的,如果是的話就把當前的元素添加到原來的tuple的後面。這樣的迴圈雖說稍顯複雜,但是竟然也能通過了。。

代碼:

class Solution(object):    def findSubsequences(self, nums):        """        :type nums: List[int]        :rtype: List[List[int]]        """        dp = set()        for n in nums:            for y in list(dp):                if n >= y[-1]:                    dp.add(y + (n,))            dp.add((n,))        return list(e for e in dp if len(e) > 1)
日期

2018 年 4 月 5 日 ———— 清明節假期開始,小長假真好~~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.