LeetCode-47-Full Arrangement II

Problem Description: Given a possibleContains repeated numbersThe sequence nums returns all non-repeating full permutations in any order.

Question link: LeetCode-47-Full Arrangement II

Problem-solving ideas: Note that the question contains repeated numbers, so duplicate removal operations are required;

  1. This question does not require startIndex, because it starts from index 0 every time, which is a permutation problem;
  2. The termination condition is path.size()==nums.length, and the results are harvested at each leaf node;
  3. The most important thing is the deduplication operation. Is it deduplication of branches or tree layers? It should be possible, but in terms of efficiency, tree layer deduplication is faster. The so-called tree layer deduplication means nums[i]==nums[i-1], and the previous element has not been used used[i -1]==false.

Code:

class Solution {
    
    
    // 和 46 全排列相比,多了2步去重的操作,树层去重
    public List<List<Integer>> permuteUnique(int[] nums) {
    
    
        Arrays.sort(nums);// 要先排序,方便处理相同的元素
        backTracking(nums, new boolean[nums.length]);
        return res;
    }

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public void backTracking(int[] nums, boolean[] used){
    
    
        if (path.size()== nums.length){
    
    
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
    
    
            // used[i-1]=true : 说明树枝前一个元素已经取过
            // used[i-1]=false : 说明树层前一个元素没有取过
            // 如果同一个树层的元素使用过,则continue
            if (i>0 && nums[i]==nums[i-1] && used[i-1]==false){
    
    // 树层去重,当前没有使用,并且和前一个数不相等
                continue;
            }
            if (used[i]){
    
    // 当前的位置还没有使用过,必须加上这个判断,不然会有很多重复的组合
                continue;
            }
            path.add(nums[i]);
            used[i]=true;
            backTracking(nums, used);
            used[i]=false;
            path.remove(path.size()-1);
        }
    }
}

おすすめ

転載: blog.csdn.net/Miss_croal/article/details/132845824