您的位置:首页 > 职场人生

LeetCode 047 Permutations II

2014-03-23 21:40 323 查看
题目

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]
.

数组全排列,数组中可能有数字重复。

思路

1 基础的解法,TLE,可以想到会有内容重复计算。

2 这里考虑一个新的方法,先排序让从小到大。这样用了O(nlgn),这样有重复的也只能出现在相邻。之后,需要一个数组,来记录相应的元素是否使用过。一旦未使用过,且和前面的元素相同,那么就可以跳过这个元素的dfs。

代码

public class Solution {
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> tmp = new ArrayList<Integer>();
int n = num.length;
boolean[] visited = new boolean
;
Arrays.sort(num);
permuteImp(res, tmp, num, visited);

return res;
}
private void permuteImp(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int[] num, boolean[] visited){
if(tmp.size() == num.length){
res.add(new ArrayList<Integer>(tmp));
return;
}
for(int i=0; i<num.length; i++){
if(visited[i]==false){
if(i>0&&num[i-1]==num[i]&&visited[i-1]==false){
continue;
}
tmp.add(num[i]);
visited[i] = true;
permuteImp(res, tmp, num, visited);
visited[i] = false;
tmp.remove(tmp.size()-1);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 面试笔试