[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;
                }
            }
        }
}

  

 

posted @   荒野第一快递员  阅读(156)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示