[leetcode]47. Permutations II,python实现
2016-06-16 16:24
429 查看
题目:
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]
]
是上一个问题http://blog.csdn.net/zl87758539/article/details/51682838的升级版:
之前那个是都是不同的数,现在要 有重复的数,
思路还是之前的思路遍历:
举个例子[1,1,2]吧
刚开始 第一个值:应该有两条路 1 和 2(注意不是1,1,2),假设设为x,y
第二个值 x后面有两条路1,2 ,y后面只有一条路 1(不是两条路1,1)
第三个值 x后面的两条路分别只有最后一个值2,1,y也一样。
第一个是 最后的结果图
第二个是 逻辑图
画个图就是:
那不一样在哪呢。
这里的同一层重复的路径不再走了
就在每次有重复的时候,比如一开始的1,1,2。所有重复路径 都合为一个。
其他的和PermutationsI都一样。
因此我们需要加一个flagList来告诉我们哪个值之前走过,还要记录上一个比如
第一个值 我已经走过一次1了,就不再走1了。
代码如下:
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]
]
是上一个问题http://blog.csdn.net/zl87758539/article/details/51682838的升级版:
之前那个是都是不同的数,现在要 有重复的数,
思路还是之前的思路遍历:
举个例子[1,1,2]吧
刚开始 第一个值:应该有两条路 1 和 2(注意不是1,1,2),假设设为x,y
第二个值 x后面有两条路1,2 ,y后面只有一条路 1(不是两条路1,1)
第三个值 x后面的两条路分别只有最后一个值2,1,y也一样。
第一个是 最后的结果图
第二个是 逻辑图
画个图就是:
那不一样在哪呢。
这里的同一层重复的路径不再走了
就在每次有重复的时候,比如一开始的1,1,2。所有重复路径 都合为一个。
其他的和PermutationsI都一样。
因此我们需要加一个flagList来告诉我们哪个值之前走过,还要记录上一个比如
第一个值 我已经走过一次1了,就不再走1了。
代码如下:
class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ self.res = [] sub = [] nums = sorted(nums) fl = [0]*len(nums) self.dfs(nums,[],fl) return self.res def dfs(self, Nums, subList,flagList): if len(subList) == len(Nums): #print res,subList self.res.append(subList[:]) last = None for idx in range(len(Nums)): m = Nums[idx] if flagList[idx]==1: continue if last == m: continue flagList[idx] = 1 subList.append(m) self.dfs(Nums,subList,flagList) last = subList.pop() flagList[idx] = 0
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Linux 中seq 命令的用法
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解