您的位置:首页 > 其它

字符串的排列和组合(不考虑字符重复的情况)

2014-06-03 15:03 323 查看
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

void permu(char *);
void permutation(char *, char *);
void combination(char *);//方法1
void combination2(char *, int);//方法2

int main()
{
char str[5] = "abc";
//	combination(str);
combination2(str,3);
//	permu(str);
system("pause");
return 0;
}

void permu(char *str)
{
if (str == NULL || str == "")
{
return;
}

permutation(str, str);

}
void permutation(char *pStr, char *pBegin)
{
char temp, *pCh = pBegin;

if (*pBegin == '\0')
{
printf("%s\n", pStr);
}
else
{
for (pCh = pBegin; *pCh != '\0'; pCh++)
{
temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;

permutation(pStr, pBegin + 1);

temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;

}
}

}

void combination(char *str)
{
int char_num = 0, flag = 0, temp = 0;
int *decial = NULL;
int i, num = 0, add = 0;
if (str == NULL || str == "")
{
return;
}

for (i = 0; str[i] !=  '\0'; i++)
{
char_num++;
}

decial = (int *)malloc((char_num + 1) * sizeof(int));

for (i = 0; i < char_num + 1; i++)
{
*(decial + i) = 0;
}

while (1)
{
add = 1;
for (i = 0; ; i++)
{
temp = decial[i] + flag + add;
decial[i] = temp % 2;
flag = temp / 2;
if (flag == 0)
{
break;
}
add = 0;
}

if (decial[char_num] == 1)
{
break;
}

for (i = 0; i < char_num + 1; i++)
{
if (decial[i] == 1)
{
printf("%c", str[i]);
}
}
printf("\n");

}
free(decial);
}

void combination2(char *str, int N)//N为字符的个数
{
int i,j;
int num  = pow(2.0, N) ;
for(i=1;i<num;i++)
{
for(j=0;j<N;j++)
{
if((i>>j)&1)
printf("%c", str[j]);
}
printf("\n");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐