惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
博客园 - 司徒正美
大猫的无限游戏
大猫的无限游戏
Last Week in AI
Last Week in AI
V
Visual Studio Blog
阮一峰的网络日志
阮一峰的网络日志
小众软件
小众软件
宝玉的分享
宝玉的分享
Apple Machine Learning Research
Apple Machine Learning Research
美团技术团队
WordPress大学
WordPress大学
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
罗磊的独立博客
The Cloudflare Blog
V
V2EX
月光博客
月光博客
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
GbyAI
GbyAI
博客园 - 【当耐特】
T
Tailwind CSS Blog

博客园 - Dabay

[Leetcode][Python]56: Merge Intervals [Leetcode][Python]55: Jump Game [Leetcode][Python]54: Spiral Matrix [Leetcode][Python]53: Maximum Subarray [Leetcode][Python]52: N-Queens II [Leetcode][Python]51: N-Queens [Leetcode][Python]50: Pow(x, n) [Leetcode][Python]49: Anagrams [Leetcode][Python]48: Rotate Image [Leetcode][Python]46: Permutations [Leetcode][Python]45: Jump Game II [Leetcode][Python]44:Wildcard Matching [Leetcode][Python]43: Multiply Strings [Leetcode][Python]42: Trapping Rain Water [Leetcode][Python]41: First Missing Positive [Leetcode][Python]40: Combination Sum II [Leetcode][Python]39: Combination Sum [Leetcode][Python]19: Remove Nth Node From End of List [Leetcode][Python]37: Sudoku Solver
[Leetcode][Python]47: Permutations II
Dabay · 2015-03-25 · via 博客园 - Dabay
# -*- coding: utf8 -*-
'''
__author__ = 'dabay.wang@gmail.com'

47: Permutations II
https://oj.leetcode.com/problems/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], and [2,1,1].

===Comments by Dabay===
先排序,然后DFS。
注意去重,如果进入了一次DFS,用pre记录上次用的数字。这个pre只在DFS中的for中有效,所以每次进入进入新的DFS的时候,重新设置为None.
'''

class Solution:
# @param num, a list of integer
# @return a list of lists of integers
def permuteUnique(self, num):
res = []
num.sort()
self.DFS(res, [], None, num)
return res

def DFS(self, res, l, pre, nums):
if len(nums) == 0:
res.append(list(l))
pre = None
for i in xrange(len(nums)):
if nums[i] == pre:
continue
l.append(nums[i])
self.DFS(res, l, nums[i], nums[:i] + nums[i+1:])
l.pop()
pre = nums[i]

def main():
sol = Solution()
nums = [1,1,2]
print sol.permuteUnique(nums)

if __name__ == "__main__":
import time
start = time.clock()
main()
print "%s sec" % (time.clock() - start)