47. 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].
链接: http://leetcode.com/problems/permutations-ii/
题解:
求全排列,但元素可能有重复。去重复就成为了关键。今天好好思考了一下dfs+回溯,比如1134,最外层就是求出第一个元素,比如 1, 2, 3, 里面的嵌套dfs再负责第二,三,四个元素。 去重复的方法是传递一个visited数组,把排序后相同的元素看成一个cluster,假如nums[i] == nums[i - 1],但i-1没有被访问过,说明整个cluster不被访问,跳过整个cluster。
Time complexity - O(n!), Space Complexity - O(n)。
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums == null || nums.length == 0)
return res;
Arrays.sort(nums);
ArrayList<Integer> list = new ArrayList<Integer>();
boolean[] visited = new boolean[nums.length];
dfs(res, list, nums, visited);
return res;
}
private void dfs(List<List<Integer>> res, ArrayList<Integer> list, int[] nums, boolean[] visited) {
if(list.size() == nums.length) {
res.add(new ArrayList<Integer>(list));
return;
}
for(int i = 0; i < nums.length; i++) {
if(visited[i] || (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1])) //skip duplicates
continue;
if(!visited[i]) {
visited[i] = true;
list.add(nums[i]);
dfs(res, list, nums, visited);
list.remove(list.size() - 1);
visited[i] = false;
}
}
}
}
二刷:
Java:
DFS + Backtracking:
一刷写的一坨屎...这遍依然不清不楚。 主要还是用了Permutation的代码,不同的地方是,我们使用了一个数组 - boolean[] visited。这个数组用来在dfs过程中记录已经访问过的值来避免计算重复。同时我们在dfs和backtracking的时候也要回溯这个数组。 经过上述步骤,我们就可以避免在dfs的时候有重复了。比如输入数组为[1, 1, 1], 则这个最后的结果 {[1, 1, 1]}是在最外层被加入到res中去的。 我们也要注意在遍历数组的时候,假如 visited[i]或者(i > 0 && nums[i] == nums[i - 1] && visited[i - 1]),要continue。
Time Complexity - O(n!), Space Complexity - O(n)
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
Arrays.sort(nums);
boolean[] visited = new boolean[nums.length];
permuteUnique(res, new ArrayList<Integer>(), visited, nums);
return res;
}
private void permuteUnique(List<List<Integer>> res, List<Integer> onePerm, boolean[] visited, int[] nums) {
if (onePerm.size() == nums.length) {
res.add(new ArrayList<>(onePerm));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i] || (i > 0 && nums[i] == nums[i - 1] && visited[i - 1])) {
continue;
}
visited[i] = true;
onePerm.add(nums[i]);
permuteUnique(res, onePerm, visited, nums);
onePerm.remove(onePerm.size() - 1);
visited[i] = false;
}
}
}
Iterative: Using Next Permutation:
我们依然可以使用Permutation I里面使用了求next permutation的代码, 完全搬移,都不用改的。 时间和空间复杂度还需要好好计算一下。这里有点混。
Time Complexity - O(n!), Space Complexity - O(n)
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
Arrays.sort(nums);
Integer[] numsInt = new Integer[nums.length];
for (int i = 0; i < nums.length; i++) {
numsInt[i] = nums[i];
}
res.add(new ArrayList<>(Arrays.asList(numsInt)));
while (hasNextPermutation(numsInt)) {
res.add(new ArrayList<>(Arrays.asList(numsInt)));
}
return res;
}
private boolean hasNextPermutation(Integer[] nums) {
for (int i = nums.length - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
for (int j = nums.length - 1; j >= i; j--) {
if (nums[j] > nums[i]) {
swap(nums, i, j);
reverse(nums, i + 1, nums.length - 1);
return true;
}
}
}
}
return false;
}
private void swap(Integer[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
private void reverse(Integer[] nums, int i, int j) {
while (i < j) {
swap(nums, i++, j--);
}
}
}
三刷:
使用了和上一题一样的代码,也是next permutation的方法。
Java:
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
Arrays.sort(nums);
do {
List<Integer> permu = new ArrayList<>();
for (int num : nums) permu.add(num);
res.add(permu);
} while (hasNextPermutation(nums));
return res;
}
private boolean hasNextPermutation(int[] nums) {
int len = nums.length;
for (int i = len - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
for (int j = len - 1; j > i; j--) {
if (nums[j] > nums[i]) {
swap(nums, i, j);
reverse(nums, i + 1, len - 1);
return true;
}
}
}
}
return false;
}
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
private void reverse(int[] nums, int i, int j) {
while (i < j) swap(nums, i++, j--);
}
}
Reference:
http://www.cnblogs.com/springfor/p/3898447.html
https://leetcode.com/discuss/25279/a-simple-c-solution-in-only-20-lines
https://leetcode.com/discuss/10609/a-non-recursive-c-implementation-with-o-1-space-cost
https://leetcode.com/discuss/18482/share-my-recursive-solution
https://leetcode.com/discuss/77245/line-python-solution-with-line-handle-duplication-beat-others
https://leetcode.com/discuss/62272/ac-python-clean-solution-108-ms
https://leetcode.com/discuss/55350/short-and-clean-java-solution
47. Permutations II的更多相关文章
- [Leetcode][Python]47: Permutations II
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 47: Permutations IIhttps://oj.leetcode. ...
- leetcode46. Permutations 、47. Permutations II、 剑指offer字符串的排列
字符串排列和PermutationsII差不多 Permutations第一种解法: 这种方法从0开始遍历,通过visited来存储是否被访问到,level代表每次已经存储了多少个数字 class S ...
- 【LeetCode】47. Permutations II
Permutations II Given a collection of numbers that might contain duplicates, return all possible uni ...
- leetCode 47.Permutations II (排列组合II) 解题思路和方法
Permutations II Given a collection of numbers that might contain duplicates, return all possible un ...
- [LeetCode] 47. Permutations II 全排列之二
Given a collection of numbers that might contain duplicates, return all possible unique permutations ...
- 47. Permutations II (Back-Track, Sort)
Given a collection of numbers that might contain duplicates, return all possible unique permutations ...
- 47. Permutations II (JAVA)
Given a collection of numbers that might contain duplicates, return all possible unique permutations ...
- [leetcode] 47. Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique permutations ...
- LeetCode 【47. Permutations II】
Given a collection of numbers that might contain duplicates, return all possible unique permutations ...
随机推荐
- cadence 机械孔的制作
在平时画PCB的时候,会用到安装孔,好多人就是找个过孔,在原理图中连接GND,这样使用也可以,下面介绍一种正经机械孔的制作方法(自己摸索的),制作一个孔径为3mm的安装孔. 1 打开pad desig ...
- 用Python作GIS之二:STARS开发环境配置
STARS的一般使用可以通过REGAL网页快速学习http://regionalanalysislab.org/?n=STARS再次不做详细介绍这里关注的主题是对STARS源代码分析即为使用Pytho ...
- 一个订单相关的存储过程(MySQL)
BEGIN DECLARE currentDate VARCHAR(15) ;/*当前日期,有可能包含时分秒 */ DECLARE maxNo INT DEFAULT 0 ; /* 离现在最近的满足条 ...
- linux编码
转: Linux查看文件编码格式及文件编码转换 如果你需要在Linux中操作windows下的文件,那么你可能会经常遇到文件编码转换的问题.Windows中默认的文件格式是GBK(gb2312),而L ...
- iOS 进阶 第八天(0407)
0407 UIPickerView.UIDatePicker和UIToolBar请参见视频和代码 pch文件 #ifdef __OBJC__ //在这里面写oc的引用,比如一些oc的头文件或者NSLo ...
- Hashmap in java
1. HashMap要点: 1.1 基本数据结构: 采用 数组+链表/平衡二叉查找树 的组合形式,所有键值对都以Entry<K,V>形式存储(每put进一个键值对,就会实例化一个Entr ...
- Project Settings -> Editor 设置详解
Default Behavior Mode (默认行为模式) 定义项目在导入Assets时的默认导入设置,当设置为3D模式时,Unity假设将导入的文件创建为纹理类型(如:PNG文件):当设置为2D时 ...
- vs2013中头文件中大小写的切换的快捷键
1.选中内容 2.ctrl+shift+u 例如: #include "LayerStart.h" -> #include "LAYERSTART.H&q ...
- php中的性能挖掘
搞php以后,感觉总是很别扭,因为我觉得php会很慢,因为array普遍,在Key的循环查找不是很浪费性能么!因为我以前搞.net和java,他们是用的大多是寻址和索引方式,而php中太多是使用Key ...
- 【模板】Big-Step-Giant-Step 大步小步
求一个 的最小整数解 bsgs 当h是质数的时候使用 extbsgs 不满足上面那种情况的时候 具体参见http://tonyfang.is-programmer.com/posts/178997.h ...