当前位置: 编程技术>.net/c#/asp.net
C#组合函数的使用详解
来源: 互联网 发布时间:2014-10-22
本文导语: 如下所示: 代码如下:using System;using System.Collections.Generic;using System.Text;namespace ConsoleApplication1{ class Class1 { static string[] str = { "A", "B", "C", "D", "E" }; static void Main() { Dictionary...
如下所示:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Class1
{
static string[] str = { "A", "B", "C", "D", "E" };
static void Main()
{
Dictionary dic = new Dictionary();
//将数组元素添加到dic
for (int i = 0; i < str.Length; i++)
{
dic.Add(str[i], i);
}
GetDic(dic);
Console.ReadLine();
}
static void GetDic(Dictionary dd)
{
Dictionary dic = new Dictionary();
//主要是抓住AB,AC,AD,AE,然后就是开始从 BC,BD这样的原理用dd中的键与数组的中对应索引比dd中的value大进行组合
foreach (KeyValuePair kk in dd)
{
for (int i = kk.Value + 1; i < str.Length; i++)
{
Console.WriteLine(kk.Key + str[i]);
dic.Add(kk.Key + str[i], i);
}
}
//递归
if (dic.Count > 0) GetDic(dic);
}
}
}
结果
AB
AC
AD
AE
BC
BD
BE
CD
CE
DE
ABC
ABD
ABE
ACD
ACE
ADE
BCD
BCE
BDE
CDE
ABCD
ABCE
ABDE
ACDE
BCDE
ABCDE
代码如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Class1
{
static string[] str = { "A", "B", "C", "D", "E" };
static void Main()
{
Dictionary dic = new Dictionary();
//将数组元素添加到dic
for (int i = 0; i < str.Length; i++)
{
dic.Add(str[i], i);
}
GetDic(dic);
Console.ReadLine();
}
static void GetDic(Dictionary dd)
{
Dictionary dic = new Dictionary();
//主要是抓住AB,AC,AD,AE,然后就是开始从 BC,BD这样的原理用dd中的键与数组的中对应索引比dd中的value大进行组合
foreach (KeyValuePair kk in dd)
{
for (int i = kk.Value + 1; i < str.Length; i++)
{
Console.WriteLine(kk.Key + str[i]);
dic.Add(kk.Key + str[i], i);
}
}
//递归
if (dic.Count > 0) GetDic(dic);
}
}
}
结果
AB
AC
AD
AE
BC
BD
BE
CD
CE
DE
ABC
ABD
ABE
ACD
ACE
ADE
BCD
BCE
BDE
CDE
ABCD
ABCE
ABDE
ACDE
BCDE
ABCDE