Lintcode 15. Permutations (Medium) (Python)

Permutations

Description:

Given a list of numbers, return all possible permutations.

Example
For nums = [1,2,3], the permutations are:

[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Challenge
Do it without recursion.

Notice
You can assume that there is no duplicate numbers in the list.

Code:

1. 递归

class Solution:
    """
    @param: nums: A list of integers.
    @return: A list of permutations.
    """
    def permute(self, nums):
        # write your code here
        length = len(nums)
        if length == 0:
            return [[]]
        if length == 1:
            return [nums]
        res = []
        for i in range(length):
            for j in self.permute(nums[:i]+nums[i+1:]):
                res.append([nums[i]]+j)
        return res

猜你喜欢

转载自blog.csdn.net/weixin_41677877/article/details/82558160