剑指offer:字符串的排列(字符串全排列)

题目描述

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。 
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

class Solution {
private:
	vector vec;

public:
    vector Permutation(string str) {
        if(str.empty())
		{
			return vec;
		}

		/* 调用perm函数进行全排列 */
		perm(str,0,str.size());

		sort(vec.begin(),vec.end());
		return vec;
    }

	void perm(string str, int i , int n)
	{
		int j = 0;

		if(i == n)
		{
			vec.push_back(str);
		}
		else
		{
			for(j = i; j < n; j++)
			{
				/* 防止重复的交换 */
				if(i != j && str[i] == str[j])
				{
					continue;
				}

				swap(str[i],str[j]);
				perm(str,i+1,n);
				swap(str[i],str[j]);
			}
		}
	}
	
};

int main(void)
{
	string str("abc");
	Solution s;
	vector v;
	int i = 0;

	v = s.Permutation(str);
	for(i = 0; i < v.size(); i++)
	{
		cout << v[i] << endl;
	}
	
	
	return 0;
}


你可能感兴趣的:(经典编程题)