java 全排列去重
时间: 2023-10-17 11:06:53 浏览: 88
你可以使用递归和回溯来实现Java的全排列去重。下面是一个示例代码:
```java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Permutation {
public static List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
boolean[] visited = new boolean[nums.length];
List<Integer> permutation = new ArrayList<>();
// 先排序,保证重复的元素都相邻
Arrays.sort(nums);
backtrack(nums, visited, permutation, result);
return result;
}
private static void backtrack(int[] nums, boolean[] visited, List<Integer> permutation, List<List<Integer>> result) {
if (permutation.size() == nums.length) {
result.add(new ArrayList<>(permutation));
return;
}
for (int i = 0; i < nums.length; i++) {
// 如果当前元素已经被访问过,则跳过
if (visited[i]) {
continue;
}
// 如果当前元素与前一个元素相等,并且前一个元素未被访问过,则跳过,避免重复
if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
continue;
}
permutation.add(nums[i]);
visited[i] = true;
backtrack(nums, visited, permutation, result);
visited[i] = false;
permutation.remove(permutation.size() - 1);
}
}
public static void main(String[] args) {
int[] nums = {1, 1, 2};
List<List<Integer>> result = permuteUnique(nums);
for (List<Integer> permutation : result) {
System.out.println(permutation);
}
}
}
```
阅读全文