⭐算法OJ⭐全排列【回溯】(C++实现)Permutations II

47. Permutations II

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

Constraints:

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

Example 1:

复制代码
Input: nums = [1,1,2]
Output:
[[1,1,2],
 [1,2,1],
 [2,1,1]]

Example 2:

复制代码
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

包含重复元素的全排列问题 ,与不包含重复元素的全排列问题不同,需要避免生成重复的排列。使用回溯算法,并通过剪枝来确保生成的排列唯一。

cpp 复制代码
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// 回溯函数
void backtrack(vector<int>& nums, vector<vector<int>>& result, int start) {
    // 如果当前起始位置是数组的最后一个元素,说明找到一个排列
    if (start == nums.size()) {
        result.push_back(nums); // 将当前排列存入结果
        return;
    }

    // 用于记录当前层已经使用过的数字,避免重复
    vector<bool> used(21, false); // 数字范围在 -10 到 10 之间

    // 从起始位置开始,尝试交换元素
    for (int i = start; i < nums.size(); i++) {
        // 如果当前数字已经使用过,跳过
        if (used[nums[i] + 10]) { // +10 是为了将负数映射到正数
            continue;
        }

        used[nums[i] + 10] = true; // 标记当前数字已使用
        swap(nums[start], nums[i]); // 交换元素
        backtrack(nums, result, start + 1); // 递归到下一个位置
        swap(nums[start], nums[i]); // 回溯,撤销交换
    }
}

// 主函数:生成所有唯一排列
vector<vector<int>> permuteUnique(vector<int>& nums) {
    vector<vector<int>> result; // 存储所有唯一排列
    backtrack(nums, result, 0); // 从第 0 个位置开始回溯
    return result;
}
相关推荐
apcipot_rain2 小时前
C++转Java日记(04)
java·开发语言·c++
NEFU_Jyj2 小时前
牛客周赛R168
算法
WL学习笔记4 小时前
vector模拟实现
c++
蜗牛一步步往上爬6 小时前
第十六章 C++语言在深度学习中的应用
开发语言·c++·深度学习
likexuec9 小时前
数据结构(2)
数据结构
Navigator_Z10 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
wo_jack10 小时前
C++ 入门笔记(十六):第16课 vector 模拟实现十问十答 —— 从三指针到迭代器失效
c++·后端·面试·stl·vector
D e re k ZH10 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶11 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划