順列 C#
using System;
using System.Collections.Generic;
namespace Permutation
{
class Program
{
static void Main(string[] args)
{
new Program();
}
public Program()
{
List<int> data = new List<int> { 1, 2, 3, 4 };
List<List<int>> perm = GetPermutation(data);
foreach (List<int> p in perm) {
Console.WriteLine(string.Join(",", p));
}
}
private List<List<int>> GetPermutation(List<int> data)
{
List<List<int>> perm = new List<List<int>>();
if (data.Count == 0) {
perm.Add(data);
return perm;
}
for (int i = 0; i < data.Count; i++) {
int head = data[i];
List<int> dataCopy = new List<int>(data);
dataCopy.RemoveAt(i);
List<List<int>> childPerm = GetPermutation(dataCopy);
foreach (List<int> child in childPerm) {
child.Insert(0, head);
perm.Add(child);
}
}
return perm;
}
}
}