"Leetcode" 491. Increasing subsequences Problem solving report (Python)
tags (space-delimited): Leetcode
Topic Address: https://leetcode.com/problems/increasing-subsequences/description/ topic Description:
Given an integer array, your task are to find the different possible increasing subsequences of the Given array, and th E length of an increasing subsequence should is 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 would 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 to considered as a special case of increasing s Equence. The main effect of the topic
Finds all the incremented sequences in an array. methods of Solving problems
I first wrote Dfs practice, the result Python code timed out, this let me very uncomfortable, after all, your related topics write is Dfs ok. Then refer to the online DP practice, successfully solved.
DFS practices:
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 ()
The following is a dynamic programming code that uses a set to guarantee no duplication, and then, because the set can only put immutable objects, it is a tuple object. As we iterate through each number of the nums, we iterate over all the elements in the set to see if the last digit of each tuple element is less than or equal to the current NUM, and if so, adds the current element to the back of the original tuple. This kind of cycle, although slightly complicated, but also can pass the.
Code:
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)
Date
April 5, 2018 ———— Ching Ming holiday began, a small long vacation is really good ~ ~