46. Permutations Leetcode Python

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].



This problem is exponential. We can use one O(n) extra space to mark whether each element is used or not.

It is DFS.

class Solution:
    # @param num, a list of integer
    # @return a list of lists of integers
    def bfs(self,num,val,res,used):
        if len(val)==len(num) and val not in res:
            res.append(val)
        for i in range(len(num)):
            if used[i]==False:
                used[i]=True
                val=val+[num[i]]
                self.bfs(num,val,res,used)
                val=val[:len(val)-1]
                used[i]=False
    def permute(self, num):
        res=[]
        if len(num)==0:
            return res
        used=[False]*len(num)
        self.bfs(num,[],res,used)
        return res
        


你可能感兴趣的:(leetcode)