[LeetCode] 47. Permutations II Java
题目:
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], [2,1,1] ]
题意及分析:这道题和上一题多了一个重复值的情况,所以不能直接用元素是否在arraylist存在来作为边界条件。我这里使用一个boolean temp[nums.length]来判断nums[i]是否使用过,然后边界条件就变成 (1)当前元素没有被用过即temp[i]==false,(2)当前元素的前一个元素若没有被使用过即temp[i-1]==false,那么nums[i]!=nums[i-1],这里主要是去重。 具体看代码:
代码:
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 | public class Solution { public List<List<Integer>> permuteUnique( int [] nums) { List<List<Integer>> list= new ArrayList<>(); List<Integer> array= new ArrayList<>(); Arrays.sort(nums); int n=nums.length; boolean [] temp= new boolean [nums.length]; backtracking(list, array, 0 , n,nums,temp); return list; } public void backtracking(List<List<Integer>> list,List<Integer> array, int t, int n, int [] nums, boolean [] temp) { if (t>n) return ; else if (t==n){ list.add( new ArrayList<>(array)); } else { for ( int i= 0 ;i<n;i++){ if (temp[i]||(i> 0 &&nums[i]==nums[i- 1 ]&&!temp[i- 1 ])) continue ; array.add(nums[i]); temp[i]= true ; backtracking(list, array, t+ 1 , n, nums,temp); array.remove(array.size()- 1 ); temp[i]= false ; } } } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步