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]
.
原题链接:https://oj.leetcode.com/problems/permutations-ii/
题目:给定一组包含重复元素的集合,返回所有可能的独立排列。
思路:此题只要将之前的全排列那题稍作修改即可,首先将数组排序,这样,相同的元素就是相邻的了,在排列取元素时,如果发现前后元素相同,则跳过相同的值。
public List<List<Integer>> permuteUnique(int[] num) { if (num == null) return null; List<List<Integer>> result = new ArrayList<List<Integer>>(); if (num.length == 0) return result; Arrays.sort(num); permute(num, new boolean[num.length], new ArrayList<Integer>(), result); return result; } public void permute(int[] num, boolean[] isused, ArrayList<Integer> current, List<List<Integer>> result) { if (current.size() == num.length) { result.add(new ArrayList<Integer>(current)); return; } for (int i = 0; i < num.length; i++) { if (!isused[i]) { isused[i] = true; current.add(num[i]); permute(num, isused, current, result); isused[i] = false; current.remove(current.size() - 1); while (i + 1 < num.length && num[i + 1] == num[i]) i++; } } }
时间: 2024-10-12 13:48:46