leetcode刷题笔记-回溯

491. Increasing Subsequences

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]]

套路,和以前的题目都是一个模式。一般来说回溯法速度通不过才对。

class Solution(object):
    def findSubsequences(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        self.helper(nums, 0, [], res)
        return res
    
    def helper(self, nums, index, temp, res):
        
        if len(temp) >= 2:
            res.append(temp[:])
        
        used = {}
        for i in xrange(index, len(nums)):
            # 判断递增
            if len(temp) and temp[-1] > nums[i]: continue
            # 判断同个位置是否用过
            if nums[i] not in used:
                used[nums[i]] = True
            else:
                continue
                
            self.helper(nums, i+1, temp+[nums[i]], res)

 

点赞