LeetCode 47 全排列II
给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations-ii
解法一
每次让一个数字做为首数字,剩下的递归排列。通过swap来改变首数字。
依次将待排列的集合规模变小,若某一个数字做过首字符则跳过。
如 1 2 2 3
先让1做第一个数字, 剩下子序列2 2 3进行递归
对2 2 3进行排列
可得 1 2 2 3、1 2 3 2 、1 3 2 2
当st=1,i=2时 nums[st]=2,nums[st]=2 此时进入isSwap函数判断,st=1,end=i=2,再nums[st]~nums[end-1]中出现了nums[end]的数字,说明nums[end]已经在st、st+1…,end-1位置中出现过,无需重复排列,所以continue。
class Solution {
public:
void swap(int &a,int &b){
int tmp=a;
a=b;
b=tmp;
}
bool isSwap(vector<int>& nums,int st,int end){
for(int i=st;i<end;i++){
if(nums[i]==nums[end]){
return false;
}
}
return true;
}
void curusion(int st,vector<int>& nums,int numsSize,vector<vector<int>>& res,vector<int> & tmp){
if(st==numsSize){
for(int i=0;i<numsSize;i++){
tmp.push_back