import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
perm(result, nums, 0, nums.length - 1);
return result;
}
public void perm(List<List<Integer>> result, int[] nums, int start, int end) {
Set<Integer> permed = new HashSet<>();
if (start > end) {
List<Integer> list = new ArrayList<>();
for (int num : nums) {
list.add(num);
}
result.add(list);
} else {
for (int i = start; i <= end; i++) {
if(permed.add(nums[i])) {
swap(nums, start, i);
perm(result, nums, start + 1, end);
swap(nums, start, i);
}
}
}
}
public void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
public static void main(String[] args) {
int[] nums = {1,1,2};
List<List<Integer>> result = new Solution().permute(nums);
System.out.println(result);
}
}
全排列 去重 非字典序
猜你喜欢
转载自blog.csdn.net/ok0011/article/details/52695000
今日推荐
周排行