题目来源
输入一组数字(可能包含重复数字),输出其所有的排列方式。
样例
输入:[1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
非重复数组
代码
//
// Created by Admin on 2020/8/19.
//
// 51 数字排列
/*
* 输入一组数字(可能包含重复数字),输出其所有的排列方式
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> res;
/*
* n代表 num 的size k代表递归参数
*/
void dfs(vector<int>&nums,vector<int>&temp,vector<bool>&st ,int n,int k)
{
if(k==n){
res.push_back(temp);
return;
}
for(int i=0;i<n;i++)
{
if(!st[i]){
st[i]= true;
temp.push_back(nums[i]);
dfs(nums,temp,st,n,k+1);
st[i]= false;
temp.pop_back();
}
}
return ;
}
vector<vector<int>> permutation(vector<int>& nums)
{
int n=nums.size();
vector<int> temp;
vector<bool> st(n,false);
dfs(nums,temp,st,n,0);
return res;
}
};
int main()
{
Solution s;
vector<int> nums={1,1,2};
sort(nums.begin(),nums.end());
s.permutation(nums);
auto ans=s.res;
for( auto &x: ans)
{
for(auto &y:x)
{
cout<<y<<" ";
}
printf("\n");
}
return 0;
}
重复数组考虑
重点现象深度优先遍历的搜索树 在那些地方会是重复的
在搜索之前进行排序 一旦发现这一支搜索下去 就会的得到重复元素 就停止搜索
来源 liweiwei 大佬
例如 1 1 3
重点现象深度优先遍历的搜索树 在那些地方会是重复的
在搜索之前进行排序 一旦发现这一支搜索下去 就会的得到重复元素 就停止搜索 !st[i-1] 表示 nums[i-] 在深度优先遍历的过程中刚刚撤销选择 考虑搜索树的 第二个分支
当进入到第二个搜索分支时 第一个搜索状态一定已经完全退出 所有的 113 可以重新选择
st 表示上一次的重复数字状态已经撤销归为0状态
//
// Created by Admin on 2020/8/19.
//
// 51 数字排列
/*
* 输入一组数字(可能包含重复数字),输出其所有的排列方式
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> res;
/*
* n代表 num 的size k代表递归参数
*/
void dfs(vector<int>&nums,vector<int>&temp,vector<bool>&st ,int n,int k)
{
if(k==n){
res.push_back(temp);
return;
}
for(int i=0;i<n;i++)
{
if(!st[i]){
// 1 1 3
// 重点现象深度优先遍历的搜索树 在那些地方会是重复的
// 在搜索之前进行排序 一旦发现这一支搜索下去 就会的得到重复元素 就停止搜索
// !st[i-1] 表示 nums[i-] 在深度优先遍历的过程中刚刚撤销选择 考虑搜索树的 第二个分支
// 当进入到第二个搜索分支时 第一个搜索状态一定已经完全退出 所有的 113 可以重新选择
// st 表示上一次的重复数字状态已经撤销归为0状态
if(i>0&&nums[i]==nums[i-1]&&!st[i-1]) continue;
st[i]= true;
temp.push_back(nums[i]);
dfs(nums,temp,st,n,k+1);
st[i]= false;
temp.pop_back();
}
}
return ;
}
vector<vector<int>> permutation(vector<int>& nums)
{
int n=nums.size();
vector<int> temp;
vector<bool> st(n,false);
dfs(nums,temp,st,n,0);
return res;
}
};
int main()
{
Solution s;
vector<int> nums={1,1,2};
sort(nums.begin(),nums.end());
s.permutation(nums);
auto ans=s.res;
for( auto &x: ans)
{
for(auto &y:x)
{
cout<<y<<" ";
}
printf("\n");
}
return 0;
}