剑指offer46重复数组全排列

题目来源
输入一组数字(可能包含重复数字),输出其所有的排列方式。

样例
输入:[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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值