您的位置:首页 > 其它

Permutations II - Leetcode

2015-02-19 03:34 344 查看
<pre name="code" class="java"><pre name="code" class="java">public class Solution {
public List<List<Integer>> permuteUnique(int[] num) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] visited = new boolean[num.length];
Arrays.sort(num);
DFS(num, path, result, visited);
return result;
}

private void DFS(int[] num, List<Integer> path, List<List<Integer>> result, boolean[] visited){
if(path.size() == num.length){
ArrayList<Integer> al = new ArrayList<>(path);
result.add(al);
return;
}
for(int i=0; i<num.length; i++)
{
if(i>0 && num[i]==num[i-1] && visited[i-1]==false)
continue;
if(!visited[i]){
visited[i]=true;
path.add(num[i]);
DFS(num, path, result, visited);
path.remove(path.size()-1);
visited[i]=false;
}
}
}
}





分析:这个思路是看的这里的:http://www.cnblogs.com/springfor/p/3898447.html

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]
.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: