首页 > 其他 > 详细

[LeetCode] 491. Increasing Subsequences_Medium tag: backtracking

时间:2021-06-07 20:32:25      阅读:19      评论:0      收藏:0      [点我收藏+]

Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order.

The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence.

 

Example 1:

Input: nums = [4,6,7,7]
Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]

Example 2:

Input: nums = [4,4,3,2,1]
Output: [[4,4]]

 

Constraints:

  • 1 <= nums.length <= 15
  • -100 <= nums[i] <= 100

 

Use [LeetCode] 90.Subsets II tag: backtracking 的方法,但是因为没有办法sort这个nums,所以添加一个visited,来判断是否要跳过这个元素。

Time: O(2 ^ n)     Space: O(n ^2)

code:

class Solution:
    def findSubsequences(self, nums):
        ans = []
        def helper(ans, temp, nums, pos):
            if len(temp) > 1:
                ans.append(temp)
            visited = set()
            for i in range(pos, len(nums)):
                if nums[i] in visited:
                    continue
                if not temp and nums[i] >= temp[-1]:
                    helper(ans, temp + [nums[i]], nums, i + 1)
        helper(ans, [], nums, 0)
        return ans

 

[LeetCode] 491. Increasing Subsequences_Medium tag: backtracking

原文:https://www.cnblogs.com/Johnsonxiong/p/14859977.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!