LeetCode Permutaions II

LeetCode解题之Permutaions II


原题

输出一个有反复数字的数组的全排列。

注意点:

  • 反复数字的可能导致反复的排列

样例:

输入: nums = [1, 2, 1]
输出: [[1, 1, 2], [1, 2, 1], [2, 1, 1]]

解题思路

这道题是上一题 Permutations 的加强版,如今要考虑反复的数字了,採用了偷懒的办法,先把数组排序。遍历时直接无视反复的数字,在原来的基础上仅仅要加入两行代码。

AC源代码

class Solution(object):
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        result = []
        nums.sort()
        self.get_permute([], nums, result)
        return result

    def get_permute(self, current, num, result):
        if not num:
            result.append(current + [])
            return
        for i, v in enumerate(num):
            if i - 1 >= 0 and num[i] == num[i - 1]:
                continue
            current.append(num[i])
            self.get_permute(current, num[:i] + num[i + 1:], result)
            current.pop()


if __name__ == "__main__":
    assert Solution().permuteUnique([1, 2, 1]) == [[1, 1, 2], [1, 2, 1], [2, 1, 1]]

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/llguanli/p/8909796.html