假设我有一个字符串(或者它可能是卡片组),我想通过该字符串的N个项目找到每个排列。我实现了这个算法来找到3个字符串项的所有排列。我有3" for"在那里循环,它看起来很脏。我想制作一个方法,我将传递参数,告诉我想要多少项目进行排列。听起来像递归......递归让我大吃一惊。只是无法找到一种方法来实现它。
到目前为止,这是我为3个项目的所有排列做的(工作正常,但我想根据所有排列应该有多少项来定制):
class Program
{
private static string str = "abcde";
private static int countPermutations;
private static int countCombinations;
static void Main(string[] args)
{
char[] list = str.ToCharArray();
GetAllPermutationOfNAtTime(list);
Console.WriteLine("{0} {1}", countPermutations, "permutations");
Console.WriteLine("{0} {1}", countCombinations, "combinations");
Console.ReadKey();
}
//here i finding every combination by 3 items and then
//find every permutation of each combination
private static void GetAllPermutationOfNAtTime(char[] list)
{
char[] tempList = new char[3];
for (int i = 0; i <= list.Length - 3; i++)
{
tempList[0] = list[i];
for (int j = 1; j <= list.Length - 3 + 1; j++)
{
if (j <= i)
continue;
tempList[1] = list[j];
for (int k = 2; k <= list.Length - 3 + 2; k++)
{
if (k <= j)
continue;
tempList[2] = list[k];
countCombinations++;
Permutation(tempList, 0, tempList.Length - 1);
}
}
}
}
private static void Permutation(char[] list, int start, int end)
{
if (start == end)
{
Console.WriteLine(list);
countPermutations++;
}
else
{
for (int i = start; i <= end; i++)
{
Swap(list, start, i);
Permutation(list, start + 1, end);
Swap(list, start, i);
}
}
}
private static void Swap(char[] list, int a, int b)
{
if (a == b || list[a] == list[b])
return;
char temp;
temp = list[a];
list[a] = list[b];
list[b] = temp;
}
}