leetcode: 47. Permutations II

来源:互联网 发布:天猫淘宝优惠卷代理 编辑:程序博客网 时间:2024/06/08 12:06

Q

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

Example

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

AC

# Time:  O(n * n!)# Space: O(n)class Solution(object):    def permuteUnique(self, nums):        """        :type nums: List[int]        :rtype: List[List[int]]        """        solutions = [[]]        for num in nums:            next = []            for solution in solutions:                for i in xrange(len(solution) + 1):                    candidate = solution[:i] + [num] + solution[i:]                    if candidate not in next:                        next.append(candidate)            solutions = next         return solutionsif __name__ == "__main__":    assert Solution().permuteUnique([1, 1, 2]) == [[2, 1, 1], [1, 2, 1], [1, 1, 2]]


原创粉丝点击