我成功地設計了算法來打印所有具有重複的數字的排列。但是我設計的算法存在缺陷。它只有在字符串的字符是唯一的時才起作用。用重複的數字打印所有排列的算法
有人可以幫助我在這裏字符串的字符可能不是唯一的情況下延長了算法.. 到目前爲止我的代碼:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<climits>
#include<iostream>
using namespace std;
void _perm(char *arr, char*result, int index)
{
static int count = 1;
if (index == strlen(arr))
{
cout << count++ << ". " << result << endl;
return;
}
for (int i = 0; i < strlen(arr); i++)
{
result[index] = arr[i];
_perm(arr, result, index + 1);
}
}
int compare(const void *a, const void *b)
{
return (*(char*)a - *(char*)b);
}
void perm(char *arr)
{
int n = strlen(arr);
if (n == 0)
return;
qsort(arr, n, sizeof(char), compare);
char *data = new char[n];
_perm(arr, data, 0);
free(data);
return;
}
int main()
{
char arr[] = "BACD";
perm(arr);
return 0;
}
我印刷詞典的排序方式輸出字符串。
我指的是從這個頁面的例子。
http://www.vitutor.com/statistics/combinatorics/permutations_repetition.html
謝謝。
hi @ stark92 ...檢查以下幾個方面..http://www.geeksforgeeks.org/write-ac-program-to-print-all-permutations-of-a-given-string/ – Karunakar 2014-11-03 12:40:26
@Karunakarn糾正我,如果我錯了。即使只有當字符串包含唯一的字符..只有當字符串不包含唯一字符時它將打印重複。 – starkk92 2014-11-03 13:18:26
您的代碼不打印排列(對於「ABCD」應該有4!== 24),但是從池「ABCD」中抽取四個結果,其中每個字母可能會多次使用。 – 2014-11-03 13:48:03