46. Permutations

2018-06-27  本文已影响0人  April63

和之前无数次的做法一样,用一个数组记录记录是否被访问过

class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        visit = [0 for i in range(len(nums))]
        res = []
        self.dfs(nums, visit, [], res)
        return res
    def dfs(self, nums, visit, temp, res):
        if len(temp) == len(nums):
            res.append(temp)
            return
        for i in range(len(nums)):
            if visit[i] == 0:
                visit[i] = 1
                self.dfs(nums, visit, temp+[nums[i]], res)
                visit[i] = 0
            
    

不带标志向量:

class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        self.surpport(nums, res, [])
        return res
    def surpport(self, nums, res, temp):
        if len(temp) == len(nums):
            res.append(temp[:])
            return
        for i in range(len(nums)):
            if nums[i] in temp:
                continue
            temp.append(nums[i])
            self.surpport(nums, res, temp)
            temp.pop()
    
        
上一篇下一篇

猜你喜欢

热点阅读