いろいろ書き方はありますが、与えられた配列の要素を入れ替えていくやり方を紹介します。
using System;
class Program
{
static void Main(string[] args)
{
var str = "abcde";
Permute(str.ToCharArray(), x => Console.WriteLine(new string(x)));
}
public static void Permute<T>(T[] array, Action<T[]> action)
{
Permute(array, 0, array.Length, action);
}
private static void Permute<T>(T[] array, int pos, int count, Action<T[]> action)
{
if (count == 0)
{
action(array);
return;
}
for (var i = 0; i < count; i++)
{
Swap(array, pos, pos + i);
Permute(array, pos + 1, count - 1, action);
Swap(array, pos, pos + i);
}
}
private static void Swap<T>(T[] array, int x, int y)
{
var temp = array[x];
array[x] = array[y];
array[y] = temp;
}
}