3. 全排列Ⅱ
题目描述
给定一个可包含重复数字的序列nums,按任意顺序返回所有不重复的全排列。
原题链接
https://leetcode-cn.com/problems/permutations-ii/
示例
示例1:
输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
示例2:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
复杂度
时间复杂度:O(n * n!)
空间复杂度:O(n)
代码
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> output = new ArrayList<Integer>();
for (int num : nums) {
output.add(num);
}
int n = nums.length;
backtrack(n, res, output, 0);
return res;
}
public void backtrack(int n, List<List<Integer>> res, List<Integer> output, int first) {
if (first == n && !res.contains(output)) {
res.add(new ArrayList<Integer>(output));
}
for (int i = first; i < n; i++) {
Collections.swap(output, first, i);
backtrack(n, res, output, first + 1);
Collections.swap(output, first, i);
}
}
}
本文来自博客园,作者:jsqup,转载请注明原文链接:https://www.cnblogs.com/jsqup/p/15839438.html

浙公网安备 33010602011771号