LeetCode | 0491. Increasing Subsequences遞增子序列【Python】
阿新 • • 發佈:2020-08-25
LeetCode 0491. Increasing Subsequences遞增子序列【Medium】【Python】【DFS】
Problem
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]]
Constraints:
- 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.
問題
給定一個整型陣列, 你的任務是找到所有該陣列的遞增子序列,遞增子序列的長度至少是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]]
說明:
- 給定陣列的長度不會超過15。
- 陣列中的整數範圍是 [-100,100]。
- 給定陣列中可能包含重複數字,相等的數字應該被視為遞增的一種情況。
思路
DFS
Python3程式碼
class Solution: def findSubsequences(self, nums: List[int]) -> List[List[int]]: # solution one:DFS res = [] def dfs(nums, tmp): if len(tmp) > 1: res.append(tmp) cur_pres = set() # 迴圈 nums 的索引值對 for inx, i in enumerate(nums): # 當前值已經被遍歷 if i in cur_pres: continue # 當前值可以加入組成遞增子序列 if not tmp or i >= tmp[-1]: cur_pres.add(i) dfs(nums[inx + 1:], tmp + [i]) dfs(nums, []) return res