IT/알고리즘
스트링에 대한 permutation을 구하는 알고리즘
쩐의시대
2008. 7. 15. 09:46
예를 들어, abc --> a, b, c, ab, bc, ac, abc
#include <stdio.h>
#include <string.h>
void swap(char *p1, char *p2)
{
char t;
t = *p1;
*p1 = *p2;
*p2 = t;
}
void perm(char *in, int st, int en)
{
int j = 0;
if( st == en) {
for( j = 0; j < en; j++)
printf("%c", in[j]);
printf("\n");
}
else {
/* in[st]에서 in[en]까지에 둘 이상의 순열이 있으면 이것을 순환적으로 생성 */
for( j = st; j < en; j++) {
SWAP(&in[st], &in[j]);
perm(in, st+1, en);
/* 인덱스 i와 인덱스 j의 데이터 위치의 위치 교환을 위해 원래 위치로 복귀*/
SWAP(&in[st], &in[j]);
}
}
}
#include <stdio.h>
#include <string.h>
void swap(char *p1, char *p2)
{
char t;
t = *p1;
*p1 = *p2;
*p2 = t;
}
void perm(char *in, int st, int en)
{
int j = 0;
if( st == en) {
for( j = 0; j < en; j++)
printf("%c", in[j]);
printf("\n");
}
else {
/* in[st]에서 in[en]까지에 둘 이상의 순열이 있으면 이것을 순환적으로 생성 */
for( j = st; j < en; j++) {
SWAP(&in[st], &in[j]);
perm(in, st+1, en);
/* 인덱스 i와 인덱스 j의 데이터 위치의 위치 교환을 위해 원래 위치로 복귀*/
SWAP(&in[st], &in[j]);
}
}
}