日期:2014-05-20 浏览次数:20966 次
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { List<string> list = new List<string>(); foreach (var item1 in Combo("123".ToList())) foreach (var item2 in Arrange(item1, new List<char>())) Console.WriteLine(new string(item2.ToArray())); } static IEnumerable<List<T>> Arrange<T>(List<T> source, List<T> current) { if (current.Count == source.Count) yield return current; else foreach (var item in source) if (!current.Any(x => x.Equals(item))) foreach (var item1 in Arrange(source, current.Union(new List<T>() { item }).ToList())) yield return item1; } public static IEnumerable<List<T>> Combo<T>(List<T> source) { for (int i = 1; i <= source.Count; i++) foreach (var item in _Combo(source, i)) yield return item; } static IEnumerable<List<T>> _Combo<T>(List<T> source, int len) { if (len <= 0) { yield return new List<T>(); } else { int[] pos = new int[len]; for (int i = 0; i < len; i++) pos[i] = i; while (pos[0] < source.Count - len) { List<T> newlist = new List<T>(); for (int i = 0; i < len; i++) newlist.Add(source[pos[i]]); for (int i = len - 1; i >= 0; i--) { if (pos[i] < source.Count - len + i) { pos[i]++; for (int j = i + 1; j <= len - 1; j++) pos[j] = pos[i] + j - i; break; } else { continue; } } yield return newlist; } List<T> last = new List<T>(); for (int i = source.Count - len; i < source.Count; i++) last.Add(source[i]); yield return last; } } } }