C#写的一段求子集的程序,希望高手帮忙改进

johnshen0211 2008-11-18 03:15:41
如题,程序如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;

namespace TestSubSet
{
class Program
{
static void Main(string[] args)
{
Regex r = new Regex(",");

ArrayList al = new ArrayList();
//al.Add("A,B,C,D");
al.Add("A,B,C");
Console.WriteLine("A,B,C的子集是:");
ArrayList alsubset = new ArrayList();

for (int i = 0; i < al.Count; i++)
{

string[] s = r.Split(al[i].ToString());

string str = "";
for (int j = 0; j < s.Length; j++)
str = str + s[j].ToString();

//调用求子集函数
alsubset = subSet(str);

alsubset.Sort();

//将子集进行输出
for (int j = 0; j < alsubset.Count; j++)
Console.WriteLine(alsubset[j].ToString());

}



Console.ReadLine();
}

static ArrayList subSet(string str)
{
ArrayList al = new ArrayList();

for (int i = 0; i < str.Length; ++i)
{
getSub(str, i, al);
}

return al;
}

static void getSub(string str, int i, ArrayList al)
{

str = str.Remove(i, 1);

if (!al.Contains(str) && str != "")
{
al.Add(formatStr(str));
}
else
{
return;
}

for (int j = 0; j < str.Length; ++j)
{
getSub(str, j, al);
}

}

static string formatStr(string str)
{
string fstr = str.Substring(0,1);
for (int i = 1; i < str.Length; i++)
fstr = fstr + "," + str.Substring(i, 1);
return fstr;
}
}
}
程序运行结果如下:
Console.WriteLine("A,B,C的子集是:");
A
A,B
A,C
B
B,C
C

谢谢!
...全文
92 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuezaiyue 2008-11-18
  • 打赏
  • 举报
回复
直接用位操作好了,计算ABCDEFGHIJKLMN只需一秒钟:

static void Main(string[] args)
{
string set = "ABCDEFGHIJKLMN";
string[] subsets = GetSubSet(set);
foreach (string s in subsets)
{
Console.WriteLine(s);
}
}

static string[] GetSubSet(string set)
{
List<string> subsets = new List<string>();
for (int i = 0; i < (1 << set.Length); i++)
{
string s = "";
for (int j = 0; j < set.Length; j++)
{
if ((i & (1 << j)) != 0)
{
s += set[j];
}
}
subsets.Add(s);
}
return subsets.ToArray();
}


输出:
A
B
AB
C
AC
BC
ABC
D
AD
BD
ABD
CD
ACD
BCD
ABCD
E
AE
...
ABCDEFGHIJKLMN
simen_frankly 2008-11-18
  • 打赏
  • 举报
回复
你不是都写了吗?
我说一下我的思路
首先将A,B,C以逗号split,然后放入数组中,str[1],str[2],str[3]取数全排列就是了,不知道对你是否有帮助??

111,130

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧