leetcode 47 全排列Ⅱ
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
该题思路如下:
该题采用回溯方法可解决,主要问题为重复排序去重,如**2*2**中,如果按常规方式,可能会将22视为2'2与22',此时可以选择合适的判定策略-串的连续判断,即如abc,当a未被使用时,b也不能被使用,c如此,解题思路如下
1.将nums数组设置为全局变量,并进行排序,将连续数组合并在一起
2.使用回溯算法
3.在回溯算法中加入去重条件与终止条件
4.返回list
时间复杂度为O(n!)
class Solution { int[] nums; public List<List<Integer>> permutation(int[] _nums) { List<List<Integer>> list = new ArrayList<>(); nums = _nums; Arrays.sort(nums); backTrack(list, new ArrayList<>(), new boolean[nums.length]); return list; } void backTrack(List<List<Integer>> list, List<Integer> temp, boolean[] used ){ if (temp.size() == nums.length){ list.add(new ArrayList<>(temp)); return; } for(int i = 0; i < nums.length; i++){ if (used[i] || i > 0 && nums[i] == nums[i-1] && !used[i-1]) continue; temp.add(nums[i]); used[i] = true; backTrack(list, temp, used); used[i] = false; temp.remove(temp.size() -1); } } }

浙公网安备 33010602011771号