DFS realizes the full arrangement of the collection

The set is unique, that is, each element only appears once in the set. If the number of set elements is n, then the number of combinations for permuting the set is:
Insert picture description here
dfs implementation (C++):

#include<bits\stdc++.h>
using namespace std;
vector<int> a;
int sum = 0;

bool check(vector<int>temp, int i)
{
    
    
	for (int j = 0; j < i; j++)
		if (temp[i] == temp[j])
			return 0;
	return 1;
}


void dfs(vector<int>temp, int index) {
    
    
	if (index == temp.size()) //遍历完最后一个元素,即完成了全排列
	{
    
    
		//temp完成了全排列,可对temp进行操作
		for (int i = 0; i < temp.size(); i++)
			cout << temp[i] << " " ;
		cout << endl;
		sum++;
		return;
	}
	for (int i = 0; i < temp.size(); i++) //
	{
    
    
		temp[index] = a[i]; //只看for和这句,就知道temp[index]会遍历一次数组a,对a中每个元素进行一次copy,因为后面会一个个地回溯回来
		if (check(temp,index)) //如果当前元素没和前面的元素重复
			dfs(temp,index + 1);
	}
	return; //可不加return,加了方便理解,这里是回溯的地方
}

int main()
{
    
    
	//数据输入
	int n; cin >> n;
	a.resize(n);//给a分配空间
	for (int i = 0; i < n; i++)
		cin >> a[i];

	vector<int> temp(n);
	dfs(temp, 0);
	cout <<"组合个数:"<< sum << endl;
	system("pause");
	return 0;
}


operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_42419611/article/details/105374958