【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 日 ———— 清明節假期開始,小長假真好~~