组合转排列,经过测试,找到一个可能是比较优秀的算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;

namespace DogFramework
{
/// <summary>
/// 一个简单的排列
/// </summary>
public class SimplePermute
{
public void GetPermute<T>(T[] list, Action<T[]> actAddPermute)
{
int x = list.Length - 1;
GetPermute<T>(list, 0, x, actAddPermute);
}

private void GetPermute<T>(T[] list, int k, int m, Action<T[]> actAddPermute)
{
if (k == m)
{
actAddPermute?.Invoke(list);
}
else
{
for (int i = k; i <= m; i++)
{
Swap(ref list[k], ref list[i]);
GetPermute(list, k + 1, m, actAddPermute);
Swap(ref list[k], ref list[i]);
}
}
}

void Swap<T>(ref T a, ref T b)
{
T tmp;
tmp = a;
a = b;
b = tmp;
}

public void Test()
{
string str = "ABCD";
char[] arr = str.ToCharArray();

GetPermute(arr, (p)=> { Console.WriteLine(p); });
Console.ReadKey();
}
}
}