排列(组合)算法的实现:
/// <summary>
/// 递归算法求排列
/// </summary>
/// <typeparam name="T">泛型类型</typeparam>
/// <param name="array"></param>
/// <param name="startIndex"></param>
/// <param name="endIndex"></param>
public static void GetPermutation<T>(T[] array, int startIndex, int endIndex)
{
if (startIndex == endIndex)
{
StringBuilder temp = new StringBuilder();
foreach (var item in array)
{
temp.Append(item.ToString());
}
Console.WriteLine(temp.ToString());
}
else
{
for (int i = startIndex; i <= endIndex; i++)
{
Swap(ref array[startIndex], ref array[i]);
GetPermutation<T>(array, startIndex + 1, endIndex);
Swap(ref array[i], ref array[startIndex]);
}
}
}
组合的情况:
public static void Combine(char[] array, bool[] b, int start, int end) { if (start <= end) { // 包含 array[start] b[start] = true; Combine(array, b, start + 1, end); // 不包含 array[start] b[start] = false; Combine(array, b, start + 1, end); } else { for (int i = 0; i <= end; ++i) { if (b[i]) { Console.WriteLine(array[i]); } } Console.WriteLine("-------------------------"); } }
refer:
http://www.cnblogs.com/snowdust/archive/2010/01/20/1652161.html
http://blog.csdn.net/lcl_data/article/details/5286847
http://yuyangc0008.blog.163.com/blog/static/54754220138492632191/
好文章:
http://www.cnblogs.com/luxiaoxun/archive/2012/08/08/2628153.html