一、字符串的全排列,字符串abc的全排列,
看成兩步:1、首先求所有可能出現在第一個位置的字符,可以把第一個字符和后面的字符一次交換;
2、固定第一個字符后,求后面字符的全排列,過程類似第一個字符的取法,即遞歸調用
注,在排列中去掉重復字符:確定當前字符是否需要更換時,檢查在這之前的字符是否有與其相同的字符,如果有,則說明第一個字符已經與它更換過。
vector<string> Permutation(string str) {
vector<string> res;
if (str.size() == 0)
return res;
PermutationResive(res, str, 0, str.size());
sort(res.begin(), res.end());
return res;
}
bool HasSame(string &str, int start, int i)
{
for (int j = start; j < i; ++j)
{
if (str[j] == str[i])
return true;
}
return false;
}
void PermutationResive(vector<string> &res, string &str, int start, int end)
{
if (start == end)
res.push_back(str);
else
{
for (int i = start; i < end; ++i)
{
if (!HasSame(str, start, i))
{
char temp = str[i];
str[i] = str[start];
str[start] = temp;
PermutationResive(res, str, start + 1, end);
temp = str[i];
str[i] = str[start];
str[start] = temp;
}
}
}
}
二、字符串組合:
abc的組合有a,b,c,ab,ac,bc,abc。足以說明,組合過程中有1-str.size()個長度的組合。
分析:對於輸入n個字符,則這n個字符能夠長長度為1,2,3…n的組合。求n字符中長度為m的組合,把n字符分為兩部分,第一個字符和其余字符。如果當前組合包含第一個字符,則在其余字符中選取m-1個字符;如果當期那組合不半酣第一個字符,則在其余字符中選取m個字符。把n字符組合為長度m的組合問題分解成兩個子問題,分別求n-1字符中m-1長度組合,和n-1字符中m長度組合。
對於本題的去掉重復字符串,哈哈,我用了個set~~,因為組合中重復的字符串只會是長度相同,第一個已經放進去,下一次取得話,也是要與之前取得的字符串作比較,所以set方便簡單省事,其實排列中也是可以這樣的,但是判斷是否已經交換過該字符更加提現思考的過程。
bool isSame(string &temp, char c)
{
for (int i = 0; i<temp.size(); ++i)
{
if (c == temp[i])
return true;
}
return false;
}
void Combination(string &str, string &temp, unordered_set<string> &res, int start, int num)
{
if(start > str.size())
return ;
if (num == 0)
{
res.insert(temp);
return;
}
if (start == str.size())
return;
temp += str[start];
Combination(str, temp, res, start + 1, num - 1);
temp = temp.substr(0, temp.size() - 1);
Combination(str, temp, res, start + 1, num);
}
bool func(string str1, string str2)
{
return str1.size() < str2.size();
}
vector<string> Combination(string &str)
{
assert(str.size() > 0);
unordered_set<string> res;
string temp = "";
for (int i = 1; i <= str.size(); ++i)
Combination(str, temp, res, 0, i);
vector<string> res_vec;
for (auto i: res)
res_vec.push_back(i);
sort(res_vec.begin(), res_vec.end(),func);
return res_vec;
}
