全排列 II
题目介绍
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例1:
示例2:
题目解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| package algorithm;
import java.util.ArrayList; import java.util.Arrays; import java.util.List;
public class PermutationsII { static boolean[] vis;
public static List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> ans = new ArrayList<>(); List<Integer> perm = new ArrayList<>(); vis = new boolean[nums.length]; Arrays.sort(nums); backtrack(nums, ans, 0, perm); return ans;
}
public static void backtrack(int[] nums, List<List<Integer>> ans, int idx, List<Integer> perm) { if (idx == nums.length) { ans.add(new ArrayList<>(perm)); return; } for (int i = 0; i < nums.length; ++i) { if (vis[i] || (i > 0 && nums[i] == nums[i - 1] && !vis[i - 1])) { continue; } perm.add(nums[i]); vis[i] = true;
backtrack(nums, ans, idx + 1, perm);
vis[i] = false; perm.remove(idx); } }
public static void main(String[] args) { int[] nums = {1,1,2}; System.out.println(permuteUnique(nums));
nums = new int[]{1,2,3}; System.out.println(permuteUnique(nums)); } }
|
打印:
思路:
思路上,使用回溯,排序然后排重。