剑指offer: 字符串的排列

题目描述:输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

以字典序的顺序打印就意思是以字典中的字母排序进行排序:abcdefg.....

假如输入字符串为abcd的话:

第一次以a为起点,将a与b交换  得到   bacd   

第二次以b为起点,将b与c交换,得到   cbad

使用递归的思想,记录当前位置然后进行交换。

if (index == str.size() - 1)
		{
			result.push_back(str);
		}

如果当前位置为str的最后位置,说明str中已经查找结束 ,直接pushback最后的元素即可。

if (str[i] == str[index] && i != index)
			{
				continue;
			}

这一步是进行重复检测,如果出现重复直接继续向后查找。

#include<algorithm>
class Solution {
public:
	vector<string> Permutation(string str) 
	{
		vector<string> result;
		if (str.empty())
		{
			return result; 
		}
		int index = 0;
		Arrange(str,result,index);
        //在最后得到所有的结果后要进行一次排序以确保满足字典序
		sort(str.begin(), str.end());
		return result;
	}
	
	void Arrange(string str,vector<string>& result,int index)
	{
		if (index == str.size() - 1)
		{
			result.push_back(str);
		}
		for (int i = index; i < str.size(); i++)
		{
			if (str[i] == str[index] && i != index)
			{
				continue;
			}
			swap(str[i], str[index]);
			Arrange(str, result, index + 1);
		}
	}
};

猜你喜欢

转载自blog.csdn.net/Shile975/article/details/89101302