My standard solution for Permutations using python


  • 0
    M
    class Solution:
    # @param num, a list of integer
    # @return a list of lists of integers
    def permute(self, num):
        result = [];
        vec = [];
        self.helper(result, vec, num);
        return result;
    
    def helper(self, result, vec, nums):
        if nums == []:
            result.append([ele for ele in vec]);
            return;
        for i, ele in enumerate(nums):
            vec.append(ele)
            self.helper(result, vec, nums[:i]+nums[i+1:])
            vec.pop()

  • 0
    C

    Nice solution, here is a version without using "vec" stack:

    def permute(self, nums):
        res = []
        self.dfs(nums, [], res)
        return res
        
    def dfs(self, nums, path, res):
        if not nums:
            res.append(path)
            return #backtracking
        for i in xrange(len(nums)):
            self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.