排序问题next_permutation

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Alatebloomer/article/details/82390475

利用next_permutation能够找出排序的下一个数。

next_permutation的思想是从右向左寻找两个相邻的元素,令第一个元素为*i,第二个元素为*ii,且满足*i<*ii。找到这样一组元素后,在从最尾端开始往前查找,找出第一个大于*i的元素,令为*j,将i、j元素对调,在将ii之后的所有元素颠倒排列,即可得到下一次排序。

数字两个字符串共有字符的一个规定长度排列

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<map>
using namespace std;




vector<string> passwordList(string userName, string motherName, int pwdLen)
{
	map<char, int> mp;
	vector<string> vec;
	size_t len1 = userName.size();
	size_t len2 = motherName.size();
	if (len1<pwdLen || len2<pwdLen)
		return vec;

	vector<char> vc;
	for (int i = 0; i<len1; ++i)
		mp[tolower(userName[i])] = 1;

	for (int i = 0; i<len2; ++i)
	{
		if (mp[tolower(motherName[i])] != 0)
		{
			vc.push_back(tolower(motherName[i]));
			mp[motherName[i]] = 0;
		}
	}

	string str;
	for (auto &m : vc)
	{
		str.push_back(m);
	}

	if (str.size()<pwdLen)
		return vec;

	sort(vc.begin(), vc.end(),greater<char>());
	for (auto &m : vc)
		cout << m << " ";
	cout << endl;

	vector<int> vec1(vc.size(), 1);
	
	int temp = vc.size()-pwdLen;
	while (temp--)
	{
		vec1[temp] = 0;
	}



	do
	{
		string str0;

		for (int i = vec1.size() - 1; i >= 0; --i)
		{
			if (vec1[i] == 1)
				str0.push_back(vc[i]);
		}
		vec.push_back(str0);
		
		for (auto &m : vec1)
			cout << m << " ";
		cout << endl;
		

	} while ( next_permutation( vec1.begin(), vec1.end() ));

	return vec;
}

输出

o l h e
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0
ehl
eho
elo
hlo

猜你喜欢

转载自blog.csdn.net/Alatebloomer/article/details/82390475