带重复元素的排列

xiaoxiao2021-02-28  27

思路

这道题感觉考察就是全排列,只是存储的时候使用Set存储,就能防止重复元素做完本题的感悟是:一定要掌握好java的容器,同时感觉自己对于容器的遍历掌握的不好

代码

static List<List<Integer>> list = new LinkedList<List<Integer>>(); static Set<List<Integer>> set = new HashSet<List<Integer>>(); public List<List<Integer>> permuteUnique(int[] nums) { if (nums.length == 0) { list.add(new ArrayList<Integer>()); } permutation(nums, 0, nums.length - 1); for (List<Integer>listSub : set) { list.add(listSub); } return list; } public void permutation(int[] nums, int k, int m) { if (k == m) { List<Integer> listSub = new LinkedList<Integer>(); for (int i = 0; i < nums.length; i++) { listSub.add(nums[i]); } set.add(listSub); return; } for (int j = k; j <= m; j++) { nums = swap(nums, j, k); permutation(nums, k + 1, m); nums = swap(nums, j, k); } } public int[] swap(int[] nums, int a, int b) { int temp; temp = nums[a]; nums[a] = nums[b]; nums[b] = temp; return nums; }

参考

http://blog.csdn.net/u012155875/article/details/78876252
转载请注明原文地址: https://www.6miu.com/read-2300362.html

最新回复(0)