求N个字符串的所有可能组合

gatx166 2011-12-01 03:11:46
用C# 写的
例如3个字符串
排列为3个1排 为空则显示0

例如 a,b,c 显示 a00,b00,c00,a0b,a0c.......
...全文
330 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
gatx166 2011-12-01
  • 打赏
  • 举报
回复
qianjin036a 伟大的男人!
 
gatx166 2011-12-01
  • 打赏
  • 举报
回复
  求N个字符串的所有可能组合!!!


用C# 写的
例如3个字符串
排列为3个1排 为空则显示0

例如 a,b,c 显示 a00,b00,c00,a0b,a0c.......
-晴天 2011-12-01
  • 打赏
  • 举报
回复
要那么麻烦么:
create table tb(col1 char(1),col2 char(1),col3 char(1))
insert into tb select 'a','b','c'
insert into tb select '0','0','0'
go
select a.col1+b.col2+c.col3 from tb a,tb b,tb c
/*
----
abc
a0c
ab0
a00
0bc
00c
0b0
000

(8 行受影响)

*/
go
drop table tb
gatx166 2011-12-01
  • 打赏
  • 举报
回复
用C#写 有很大用处
kidnet 2011-12-01
  • 打赏
  • 举报
回复
这是作业题还是面试题呢?
csdn_aspnet 2011-12-01
  • 打赏
  • 举报
回复
输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则输出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和cba。
分析:这是一道很好的考查对递归理解的编程题,因此在过去一年中频繁出现在各大公司的面试、笔试题中。

我们以三个字符abc为例来分析一下求字符串排列的过程。首先我们固定第一个字符a,求后面两个字符bc的排列。当两个字符bc的排列求好之后,我们把第一个字符a和后面的b交换,得到bac,接着我们固定第一个字符b,求后面两个字符ac的排列。现在是把c放到第一位置的时候了。记住前面我们已经把原先的第一个字符a和后面的b做了交换,为了保证这次c仍然是和原先处在第一位置的a交换,我们在拿c和第一个字符交换之前,先要把b和a交换回来。在交换b和a之后,再拿c和处在第一位置的a进行交换,得到cba。我们再次固定第一个字符c,求后面两个字符b、a的排列。

既然我们已经知道怎么求三个字符的排列,那么固定第一个字符之后求后面两个字符的排列,就是典型的递归思路了。

基于前面的分析,我们可以得到如下的参考代码:

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;
}
}
}

110,499

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧