1. 程式人生 > >動態規劃DP演算法實現全排列

動態規劃DP演算法實現全排列

/*
 * 全排列 
 * 無相同元素
 * 1. 取第1個元素插入空字串, 1種情況 
 * 2. 取第2個元素插入長度為1的字串, 1*2 = 2種情況, 例如 'b'插入"a",可以在'a'前, 'a'後 
 * 3. 取第3個元素插入長度為2的字串, 2*3 = 6種情況, 例如 'c'插入 "ab",可以在'a'前, 'b'前, 'b'後 
 * ...
 * n. 取第n個元素插入長度n-1的字串, n!種情況. 
 */


#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;


const int STRING_LENGTH = 6;


const int MAX_ELEMENTS_COUNT = 5;
const int MAX_ELEMENTS_COUNT_FACTORIAL = 120; 


void insert(char c, char * str, int index, char *output);


void allSequences(string source) {
int strLength = source.length();
const char *strChars = source.c_str();

char *MAP[MAX_ELEMENTS_COUNT_FACTORIAL][MAX_ELEMENTS_COUNT];

int rowSize[MAX_ELEMENTS_COUNT];
memset(rowSize, 0, sizeof(int) * MAX_ELEMENTS_COUNT);

char *firstStr = (char *)malloc(STRING_LENGTH);
sprintf(firstStr, "%c", strChars[0]);
printf("firstStr:%s\n", firstStr);
MAP[0][0] = firstStr;
rowSize[0] = 1;

for (int cInStr = 1; cInStr < strLength; ++cInStr) {
for (int num = 0; num < rowSize[cInStr-1]; ++num) {
for (int pos = 0; pos <= cInStr; ++pos) {
char *output = (char *)malloc(STRING_LENGTH);
MAP[rowSize[cInStr]][cInStr] = output;
insert(strChars[cInStr], MAP[num][cInStr-1], pos, output);
++rowSize[cInStr];
}
}
}
printf("Total count : %d\n", rowSize[strLength-1]);

// clean up
for (int i=0; i<MAX_ELEMENTS_COUNT_FACTORIAL; ++i) {
for (int j=0; j<MAX_ELEMENTS_COUNT; ++j) {
if(MAP[i][j] != 0) free(MAP[i][j]);
}
}
}


void insert(char c, char * str, int index, char *output) {
//printf("++ inserting %c into %s @ %d\n", c, str, index);
int size = sizeof(str);
if(0==index) {
*output = c;
strncpy(output+1, str, size);
} else {
strncpy(output, str, index);
char *p = output+index;
*p = c;
++p;
strncpy(p, str+index, size-index);
}
//printf("-- output:%s\n", output);
printf("%s\n", output);
}
int main() {
string source;
cin >> source;

allSequences(source);
return 0;
}