劍指offer:字符串的排列

題目描述:輸入一個字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba(結果請按字母順序輸出)。

輸入描述:輸入一個字符串,長度不超過9(可能有字符重複),字符只包括大小寫字母。

class Solution {
public:
	string tmp;
	vector<string> res;
	vector<string> per(string str)
	{
		if (str.size() == 0)
		{
			res.push_back(tmp);
			return res;
		}
		int i, j;
		string s;
		for (i = 0; i < str.size(); i++)
		{
			tmp += str[i];
			for (j = 0; j < str.size(); j++)
			{
				if (j != i)
					s += str[j];
			}
			res = per(s);
			s.clear();
			tmp = tmp.substr(0, tmp.size() - 1);
		}
		return res;
	}
	vector<string> Permutation(string str) {
		if (str.size() == 0)
			return res;
		res = per(str);
		vector <string> ::iterator it;
		sort(res.begin(), res.end());
		it = unique(res.begin(), res.end());
		if (it != res.end())
			res.erase(it, res.end());
		return res;
	}
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章