您的位置:首页 > 其它

字符串排列和组合的问题

2015-04-08 20:10 501 查看
1、题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则输出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和cba。
解决方法:递归,分成第一个字符和后面部分的字符。先分析所有第一个字符的情况,然后固定第一个字符,递归求出后面n-1个字符

void Permutation(char* pStr, char* pBegin);

/////////////////////////////////////////////////////////////////////////
// Get the permutation of a string,
// for example, input string abc, its permutation is
// abc acb bac bca cba cab
/////////////////////////////////////////////////////////////////////////
void Permutation(char* pStr)
{
Permutation(pStr, pStr);
}

/////////////////////////////////////////////////////////////////////////
// Print the permutation of a string,
// Input: pStr - input string
// pBegin - points to the begin char of string
// which we want to permutate in this recursion
/////////////////////////////////////////////////////////////////////////
void Permutation(char* pStr, char* pBegin)
{
if(!pStr || !pBegin)
return;

// if pBegin points to the end of string,
// this round of permutation is finished,
// print the permuted string
if(*pBegin == '\0')
{
printf("%s\n", pStr);
}
// otherwise, permute string
else
{
for(char* pCh = pBegin; *pCh != '\0'; ++ pCh)
{
// swap pCh and pBegin
char temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;

Permutation(pStr, pBegin + 1);

// restore pCh and pBegin
temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
}
}
}
2、如果不是求字符的所有排列,而是求字符的所有组合,应该怎么办呢?当输入的字符串中含有相同的字符串时,相同的字符交换位置是不同的排列,但是同一个组合。举个例子,如果输入abc,它的组合有a、b、c、ab、ac、bc、abc。
解法分析:问题简化成求n个字符的长度为m的组合,同样的吧n个字符分成两个部分:第一个字符和其余的所有字符。如果组合里包含第一个字符,则下一步在剩余的字符里选取m-1个字符;如果组合里不包含第一个字符,则下一步在剩余的n-1个字符里选取m个字符。然后两个子问题用递归的方法来解决。

void perm(string s, int m, vector<char> &result){
if (m == 0){
auto iter = result.begin();
for ( ; iter != result.end(); iter++){
cout << *iter;
}
cout << endl;
return;
}

if ( s.empty() ){
return;
}

result.push_back(s[0]);
perm(s.substr(1, s[s.size() - 1]), m - 1, result);

result.pop_back();
perm(s.substr(1, s[s.size() - 1]), m, result);
}
void combination(string s){
if (s.empty()){
return;
}

int length = s.size();
vector<char> result;
for (int i = 1; i <= length; ++i){
perm(s, i, result);
}

不过代码中没有考虑字符串中含有空格的情况,即“ 1234”或者“12 34”的情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: