[LeetCode] Permutations II

些許時間沒更新blog了XD

這次放LeetCode來分享好了

https://leetcode.com/problems/permutations-ii/

其實這題延續第一題

https://leetcode.com/problems/permutations/

第一題用DFS做就好了

那第二題其實也不用改太多,在同一個node下,跳過相同value的subnode就好了

class Solution(object):
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res=[]
        nums.sort()
        self.dfs(nums, res, [], len(nums))
        return res
    
    def dfs(self, nums, res, current,length):
        if not nums:
            res.append(current)
        else:
            prev = nums[0]
            for i in range(length):
                if prev == nums[i] and i != 0:
                    continue
                else:        
                    self.dfs(nums[:i]+nums[i+1:], res, current+[nums[i]],length-1)
                    prev = nums[i]

用python寫可以跳過整理array的部分比C方便多惹….

但複雜度應該沒甚麼影響都一樣慢XD