leetcode47
题目
解题思路
分析:要求获得可重集全排列
该题通过递归解决,实现时需要注意几点
- 同一层的重复元素不进行递归
- 查看是否已经使用完当前元素,如果全部使用完了,也不进行递归
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 49 50
| public class Solution { private List<List<Integer>> list = new ArrayList<List<Integer>>(); public List<List<Integer>> permuteUnique(int[] nums) { Arrays.sort(nums); permute(nums,new int[nums.length], 0); return list; } private void permute(int[] nums,int[] A, int cur) { if(cur==nums.length) { list.add(toList(A)); }else { for(int i=0;i<nums.length;i++) { if(i==0||nums[i]!=nums[i-1]) { int c1 = 0; int c2 = 0; for(int j = 0; j<cur;j++) { System.out.println("cur="+cur+","+A[j]); if(nums[i]==A[j])c1++; } for(int j=0;j<nums.length;j++) { if(nums[i]==nums[j])c2++; } if(c1<c2) { A[cur] = nums[i]; permute(nums, A, cur+1); } } } } }
public List toList(int[] nums) { ArrayList<Object> arrayList = new ArrayList<>(); for(Integer e: nums) { arrayList.add(e); } return arrayList; } public static void main(String[] args) { int[] nums = {1,1,2}; System.out.println(new Solution().permuteUnique(nums).toString()); } }
|