给定一个可包含重复数字的序列 arr ,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:arr = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
示例 2:
输入:arr = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
package com.loo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class BacktrackingAlgorithmII {
/**
* @param args
*/
public static void main(String[] args) {
int[] arr = new int[] { 1 , 2 , 3};
List<List<Integer>> list = getBacktracking2(arr);
System.out.println(list);
}
public static List<List<Integer>> getBacktracking2(int[] arr) {
List<List<Integer>> list = new ArrayList();
if (arr == null || arr.length == 0) {
return list;
}
boolean[] used2 = new boolean[arr.length];
List<Integer> path = new ArrayList();
Arrays.sort(arr);
dfs2(arr , arr.length , 0 , path , list , used2);
return list;
}
public static void dfs2(int[] arr , int length , int depth , List<Integer> path , List<List<Integer>> res , boolean[] used2) {
if (depth == length) {
res.add(new ArrayList<>(path));
return;
}
for (int i=0;i<length;i++) {
if (used2[i] || (i>0&&arr[i]==arr[i-1]&&!used2[i-1])) {
continue;
}
used2[i] = true;
path.add(arr[i]);
dfs2(arr , length , depth+1 , path , res , used2);
used2[i] = false;
// System.out.println(depth == path.size()-1);
// path.remove(path.size()-1);
path.remove(depth);
}
}
}