C#组合函数的使用详解
程序员文章站
2024-02-13 15:26:22
如下所示:复制代码 代码如下:using system;using system.collections.generic;using system.text;namespa...
如下所示:
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<string, int> dic = new dictionary<string, int>();
//将数组元素添加到dic
for (int i = 0; i < str.length; i++)
{
dic.add(str[i], i);
}
getdic(dic);
console.readline();
}
static void getdic(dictionary<string, int> dd)
{
dictionary<string, int> dic = new dictionary<string, int>();
//主要是抓住ab,ac,ad,ae,然后就是开始从 bc,bd这样的原理用dd中的键与数组的中对应索引比dd中的value大进行组合
foreach (keyvaluepair<string, int> 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<string, int> dic = new dictionary<string, int>();
//将数组元素添加到dic
for (int i = 0; i < str.length; i++)
{
dic.add(str[i], i);
}
getdic(dic);
console.readline();
}
static void getdic(dictionary<string, int> dd)
{
dictionary<string, int> dic = new dictionary<string, int>();
//主要是抓住ab,ac,ad,ae,然后就是开始从 bc,bd这样的原理用dd中的键与数组的中对应索引比dd中的value大进行组合
foreach (keyvaluepair<string, int> 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