LeetCode-Permutations & Permutations II

两个全排列问题。

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].
解题思路:穷举一个集合的全排列。这个就是python递归巧妙的使用了。

Solution

参考链接:https://discuss.leetcode.com/topic/6377/my-ac-simple-iterative-java-python-solution

# 新的元素可以插入已有排列的任何一个位置。
# iteratively
class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        perms = [[]]
        for n in nums:
            new_perms = []
            for perm in perms:
                for i in range(len(perm) + 1):
                    new_perms.append(perm[:i] + [n] + perm[i:])
            perms = new_perms
        return perms
# recursively
def permute(self, num):
    if len(num) < 2:
        return [num]
    ret = []
    for permu in self.permute(num[:-1]):
        ret += [permu[:i] + [num[-1]] + permu[i:] for i in range(len(permu) + 1)]
    return ret

参考链接:https://discuss.leetcode.com/topic/4091/a-python-code-for-permutation

 class Solution:
# @param num, a list of integer
# @return a list of lists of integers
def permute(self, num):
    if len(num)==0:
        return []
        
    result=[]
    start=[]

    def recursiveperm(list,final,temp):
        length=len(list)

        if length==0:
            final.append(temp)
            return

        for i in range(length):
            nexttemp=temp[:]
            nexttemp.append(list[i])
            templist=list[:]
            templist.pop(i)
            recursiveperm(templist,final,nexttemp)

    recursiveperm(num,result,start)
    return result

47. Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[[1,1,2],[1,2,1],[2,1,1]]

Solution

class Solution(object):
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        perms = [[]]
        for n in nums:
            new_perms = []
            for perm in perms:
                for i in range(len(perm) + 1):
                    new_perms.append(perm[:i] + [n] + perm[i:])
                    if i < len(perm) and perm[i] == n: # handles duplication
                        break
            perms = new_perms
        return perms
posted @ 2016-11-28 16:28  BinWone  阅读(139)  评论(0编辑  收藏  举报