【LeetCode】 47. Permutations II 全排列 II(Medium)(JAVA)
题目地址: https://leetcode.com/problems/permutations-ii/
题目描述:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
题目大意
给定一个可包含重复数字的序列,返回所有不重复的全排列。
解题方法
和 【LeetCode】 46. Permutations 全排列(Medium)(JAVA) 差不多,只是多了重复的元素,所以只要防止重复即可。
为了防止重复,先排序,然后过滤:if (i > 0 && list.get(i - 1) == list.get(i)) continue;
其他和上一题相同
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
List<Integer> cur = new ArrayList<>();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
list.add(nums[i]);
}
pH(res, cur, list);
return res;
}
public void pH(List<List<Integer>> res, List<Integer> cur, List<Integer> list) {
if (list.size() == 0) {
res.add(new ArrayList<Integer>(cur));
return;
}
for (int i = 0; i < list.size(); i++) {
if (i > 0 && list.get(i - 1) == list.get(i)) continue;
int temp = list.remove(i);
cur.add(temp);
pH(res, cur, list);
cur.remove(cur.size() - 1);
list.add(i, temp);
}
}
}
执行用时 : 2 ms, 在所有 Java 提交中击败了 93.20% 的用户
内存消耗 : 41.5 MB, 在所有 Java 提交中击败了 16.66% 的用户