【LEETCODE】46-Permutations

Given a collection of distinct 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].


题意:

给一组离散的数字,返回所有组合形式


参考:

http://www.cnblogs.com/zuoyuan/p/3758816.html


思路:

递归:提出 i,剩余的 nums[:i]+nums[i+1:] 去递归组合


Python

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


你可能感兴趣的:(LeetCode,python)