解决方案 »
- 讨论求教::《C#程序设计》(赵震奇主编)-项目六:中国体彩“22选5”
- 读取ini文件与SQL 数据库的效率比较
- 怎么对IEnumerable的记录 增删改
- 一个关于字符串搜索的问题
- 交流一下大家在csdn的升级时间?
- @@@@@@@@@@@@如果一个端口已经被一个套接字监听,那么用另外一个套接字再次监听这个端口,会异常。那么请问如何判断这个端口正在监听,或
- Datagrid
- 关于session
- 关于datagrid的问题,已经晕了!!!
- 异步Upd Socket编程例子,十万火急!!!!
- 我构建了个hashtable,是否能存入高级缓存,以提高程序查询速度?
- 用什么方式能实现与所有类型(主流)数据库通信?
代码都来自 http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n如果可以用LINQ,最简单的代码是:public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
{
return k == 0 ? new[] { new T[0] } :
elements.SelectMany((e, i) =>
elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] {e}).Concat(c)));
}如果不用LINQ,可以用稍复杂点的枚举器:static IEnumerable<string> Combinations(List<string> characters, int length)
{
for (int i = 0; i < characters.Count; i++)
{
if (length == 1)
yield return characters[i];
else
foreach (string next in Combinations(characters.GetRange(i + 1, characters.Count - (i + 1)), length - 1))
yield return characters[i] + next;
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int n = 3;
string[] are = { "1", "2", "3", "4", "5", "6" };
var result = are.Select(x => new string[] { x });
for (int i = 0; i < n - 1; i++)
{
result = result.SelectMany(x => are.Where(y => y.CompareTo(x.First()) < 0).Select(y => new string[] { y }.Concat(x).ToArray()));
}
foreach (var item in result)
{
Console.WriteLine(string.Join(", ", item));
}
}
}
}
关键代码只要2行。不需要递归。
google M选N caozhy 排第一的就是。
{
return Combinations(characters, 0, characters.Length - 1, length);
} static IEnumerable<List<string>> Combinations(string[] characters, int start, int end, int length)
{
if (end < start)
yield break;
else if (length == 1)
for (var i = start; i <= end; i++)
yield return new List<string> { characters[i] };
else
{
foreach (var r in Combinations(characters, start, end - 1, length))
yield return r;
foreach (var r in Combinations(characters, start, end - 1, length - 1))
{
r.Add(characters[end]);
yield return r;
}
}
}比如说你可以测试static void Main(string[] args)
{
string[] are = { "A", "B", "B" };
var result = Combinations(are, 2);
foreach (var x in result)
{
foreach (var y in x)
Console.Write(y);
Console.WriteLine();
}
Console.WriteLine("___________按任意键退出");
Console.ReadKey();
}