UVa 10063 - Knuth's Permutation

题目:克努斯序列,生成排列组合的方法。

            初始一个空串,每次用新的字符插入到上一次的所有串的组合情况中。

分析:递归、链表。利用链表储存,直接递归求解即可。

说明:貌似最后一组输出后有没有空格都可以,貌似没有空行的数据。

#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>

using namespace std;

char data[11];
char save[3628800][11];
int  used[11];

typedef struct noded
{
	char   data;
	noded* next;
}dnode;
dnode  D[11];
dnode* Head;

int  Count;
void dfs( int d, int n )
{
	if ( d == n ) {
		dnode* p = Head;
		for ( int i = 0 ; i < n ; ++ i ) {
			save[Count][i] = p->data;
			p = p->next;
		}
		save[Count ++][n] = 0;
		return;
	}
	dnode *p = Head,*q = p;
	for ( int i = 0 ; i <= d ; ++ i ) {
		//插点 
		D[d].data = data[d];
		D[d].next = p;
		if ( !i ) Head = &D[d];
		else q->next = &D[d];
		//递归 
		dfs( d+1, n );
		//回溯 
		if ( !i ) Head = p;
		else q->next = p;
		
		q = p;
		if ( i < d ) p = p->next;
	}
}

int main()
{
	int count = 0; 
	while ( scanf("%s",data) != EOF ) {
		if ( count ++ ) printf("\n");
		
		Count = 1;
		memset( save, 0, sizeof(save) );
		dfs( 0, strlen(data) );
		
		for ( int i = 1 ; i < Count ; ++ i )
			printf("%s\n",save[i]);
	}
	return 0;
}

你可能感兴趣的:(UVa 10063 - Knuth's Permutation)