LeetCode46. 全排列 两种方法:(DFS) + (import itertools)

LeetCode46. 全排列(DFS)

class Solution:
    def __init__(self):
        self.v = None
        self.n = None
        self.tmp = []
        self.ans = []

    def permute(self, nums):
        self.n = len(nums)
        self.v = [False for _ in range(self.n)]
        self.tmp = [0 for _ in range(self.n)]
        self.dfs(nums, 0)
        return self.ans

    def dfs(self, nums, depth):
        if depth == self.n:
            self.ans.append(self.tmp.copy())
            return
        else:
            for i in range(self.n):
                if not self.v[i]:
                    self.v[i] = True
                    self.tmp[depth] = nums[i]
                    self.dfs(nums, depth + 1)
                    self.v[i] = False

if __name__ == '__main__':
    a = [1, 2, 3]
    s = Solution()
    print(s.permute(a))
  • result

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
  • 简易版
import itertools


class Solution:
    def permute(self, nums):
        tmp = list(itertools.permutations(nums))
        ans = [list(t) for t in tmp]
        return ans


if __name__ == '__main__':
    a = [1, 2, 3]
    s = Solution()
    print(s.permute(a))

你可能感兴趣的:(Python,DFS,LeetCode,图论)