Permutations II

本文介绍了一种算法,用于找出包含重复数字的集合的所有唯一全排列。通过对数组进行排序并使用特定条件跳过重复元素,该算法能高效地生成不重复的全排列结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、问题描述

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]
]

二、思路

思路和Permutations类似,不同的是,由于有重复元素,我们先对数组进行排序,这样可以保证重复元素相邻,然后在for循环中添加

if(begin != i && nums[i] == nums[begin])  continue;

作用是去除掉重复排列情况。还有就是我们在求出下一个全排列后,不需要交换回来,即没有增加交换。

三、代码

class Solution {
public:
    void AllRange(vector<int> nums, int begin,int end, vector<vector<int>> &v){
        if(begin == end - 1){
            v.push_back(nums);
            return;
        }else{
            for(int i = begin; i < end; ++i){
                if(begin != i && nums[i] == nums[begin])  continue;
                swap(nums[begin], nums[i]);
                AllRange(nums, begin + 1, end, v);
            }
        }
    }
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int>> v;
        sort(nums.begin(), nums.end());
        AllRange(nums,0,nums.size(),v);
        return v;
    }
};


### Python 排列组合的使用方法与实例 Python 提供了 `itertools` 模块用于高效循环的各种工具函数。其中,`permutations` 函数可以用来生成给定序列的所有可能排列。 #### 导入 itertools 和 使用 permutations 为了使用排列功能,首先需要导入 `itertools` 模块中的 `permutations` 方法: ```python from itertools import permutations ``` #### 基本用法 当调用 `permutations(iterable, r=None)` 时,该函数返回长度为 `r` 的项迭代器;如果没有提供 `r` 参数,则默认等于可迭代对象的长度。每次迭代都会给出一个新的元组表示一种新的排列方式[^2]。 下面是一个简单的例子展示如何获取列表 `[1, 2, 3]` 中所有元素的不同顺序: ```python for p in permutations([1, 2, 3]): print(p) ``` 这会打印出如下结果: ``` (1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 1, 2) (3, 2, 1) ``` #### 设置排列长度 还可以通过传递第二个参数来设置每种排列的具体长度。比如只想要两个数目的排列情况: ```python print(list(permutations('ABCD', 2))) ``` 这段代码将会输出: ``` [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'A'), ('B', 'C'), ('B', 'D'), ('C', 'A'), ('C', 'B'), ('C', 'D'), ('D', 'A'), ('D', 'B'), ('D', 'C')] ``` #### 应用场景举例 假设有一个问题是要找出由字符 `'ABC'` 组成的所有三位字母串,并检查这些字符串是否满足某些条件(例如不含有重复字符)。那么就可以利用 `permutations` 来解决这个问题: ```python def has_unique_chars(s): """Check if string s contains all unique characters.""" return len(set(s)) == len(s) perms = [''.join(p) for p in permutations('ABC', 3)] filtered_perms = [p for p in perms if has_unique_chars(p)] print(filtered_perms) ``` 上述程序将创建一个包含所有符合条件的结果列表。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fullstack_lth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值