[Leetcode]Permutations II
来源:互联网 发布:害怕体检怎么办啊 知乎 编辑:程序博客网 时间:2024/05/11 04:47
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]
, and [2,1,1]
.
Permutations的扩展题,不同的是这题里可能会出现重复元素~解法其实也是类似的,注意处理重复元素就可以了~ 先对数组排序,然后判断当前元素是否与上一个元素相同~
class Solution: # @param num, a list of integer # @return a list of lists of integers def permuteUnique(self, num): if num is None or len(num) == 0: return [] if len(num) == 1: return [num] num.sort() res = []; prev = None for i in xrange(len(num)): if num[i] == prev: continue prev = num[i] for j in self.permuteUnique(num[:i] + num[i + 1:]): res.append([num[i]] + j) return res
class Solution: # @param num, a list of integer # @return a list of lists of integers def permuteUnique(self, num): if num is None or len(num) == 0: return [] if len(num) == 1: return [num] num.sort() self.res = [] self.helper(num, [False] * len(num), []) return self.res def helper(self, num, used, item): if len(item) == len(num): self.res.append(item) return for i in xrange(len(num)): if i > 0 and not used[i - 1] and num[i] == num[i - 1]: continue if not used[i]: used[i] = True self.helper(num, used, item + [num[i]]) used[i] = False
0 0
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- Leetcode: Permutations and Permutations II
- leetcode-permutations and permutations II
- Leetcode:Permutations与Permutations II
- LeetCode: Permutations II
- LeetCode Permutations II
- LeetCode: Permutations II
- [Leetcode] Permutations II
- [LeetCode] Permutations II
- [Leetcode] Permutations II
- leetcode Permutations II
- [LeetCode]Permutations II
- leetcode - Permutations II
- LeetCode-Permutations II
- [leetcode] Permutations II
- hdu 2084 & POJ 1163 数塔 (dp)
- Maven初识
- spring security 粗识
- 【Peking University Online Judge】1003(Hangover)
- POJ 1860 Currency Exchange
- [Leetcode]Permutations II
- 英语快照有感
- Python标准库:内置函数object()
- 【Peking University Online Judge】1004(Financial Management)
- 深度学习研究理解5:Visualizing and Understanding Convolutional Networks
- 产品原型开发
- poj 1702 模拟(用三进制砝码测量物体质量)
- 1003_我要通过!(20)
- Linux监控系统开发详解(三)--LCD驱动分析