leetcode刷题:回溯算法13(全排列 II)

46 篇文章 0 订阅
11 篇文章 0 订阅

47.全排列 II

力扣题目链接

给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。

示例 1:

  • 输入:nums = [1,1,2]
  • 输出:
    [[1,1,2],
    [1,2,1],
    [2,1,1]]

示例 2:

  • 输入:nums = [1,2,3]
  • 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

提示:

  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10

需要使用 used 数组来判断 相同的之前的 元素 有没有被使用过。如果被使用过就跳过这个元素。

        for (int i = 0; i < nums.length; i++) {
            //如果当前元素和之前元素一样,并且   之前的元素被使用过
            if (i > 0 && nums[i] == nums[i - 1] && used[i-1]) {
                continue;
            }
            if (!used[i]) {
                //如果没被使用
                used[i] = true;
                path.add(nums[i]);
                backtracking(nums, used);
                //回溯
                used[i] = false;
                path.remove(path.size() - 1);
            }
        }

回溯真的好难。。。。

package com.programmercarl.backtracking;

import java.util.*;

/**
 * @ClassName PermuteUnique
 * @Descriotion TODO
 * @Author nitaotao
 * @Date 2022/7/11 13:03
 * @Version 1.0
 * https://leetcode.cn/problems/permutations-ii/
 * 47. 全排列 II
 **/
public class PermuteUnique {
    /**
     * 给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
     *
     * @param nums
     * @return
     */
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        //先排序
        Arrays.sort(nums);
        boolean[] used = new boolean[nums.length];
        // true 代表被使用过,false 代表没被用过
        Arrays.fill(used, false);
        backtracking(nums, used);
        return result;
    }

    public void backtracking(int[] nums, boolean[] used) {
        if (nums.length == path.size()) {
            result.add(new ArrayList(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            //如果当前元素和之前元素一样,并且   之前的元素被使用过
            if (i > 0 && nums[i] == nums[i - 1] && used[i-1]) {
                continue;
            }
            if (!used[i]) {
                //如果没被使用
                used[i] = true;
                path.add(nums[i]);
                backtracking(nums, used);
                //回溯
                used[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new PermuteUnique().permuteUnique(new int[]{1, 1, 2}));
    }
}

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值