怎么求一个集合中所有元素的组合?
怎么求一个集合中所有元素的组合?比如 List<int> list={1,2,3};
要算出:{1},{2},{3},{1,2},{1,3},{2,3},{1,2,3}
--------------------编程问答--------------------
string[] Sample = new string[] { "0", "1", "2", "3", "4"};--------------------编程问答--------------------
List<string> SampleList = new List<string>();
SampleList.AddRange(Sample);
List<string> result = getCombination(SampleList, 2);
private List<string> getCombination(List<string> SampleList, int m)
{
if (m == 1)
{
return SampleList;
}
List<string> result = new List<string>();
if (SampleList.Count == m)
{
StringBuilder temp_sb = new StringBuilder();
foreach (string s in SampleList)
{
temp_sb.Append(s);
}
result.Add(temp_sb.ToString());
Console.WriteLine(temp_sb.ToString());
return result;
}
string temp_firstelement = SampleList[0];
SampleList.RemoveAt(0);
List<string> temp_samplist1 = new List<string>();
temp_samplist1.AddRange(SampleList);
List<string> temp_list1 = getCombination(temp_samplist1, m - 1);
foreach (string s in temp_list1)
{
result.Add(temp_firstelement + s);
Console.WriteLine(temp_firstelement + s);
}
List<string> temp_samplist2 = new List<string>();
temp_samplist2.AddRange(SampleList);
List<string> temp_list2 = getCombination(temp_samplist2, m);
result.AddRange(temp_list2);
return result;
}
static string[] m_Data = { "1", "2", "3", "4", "5" };--------------------编程问答-------------------- 3个元素的组合就是 2的3次方减一,7种。
void Main()
{
Dictionary<string, int> dic = new Dictionary<string, int>();
for (int i = 0; i < m_Data.Length; i++)
{
Console.WriteLine(m_Data[i]);//如果不需要打印单元素的组合,将此句注释掉
dic.Add(m_Data[i], i);
}
GetString(dic);
/*
1
2
3
4
5
12
13
14
15
23
24
25
34
35
45
123
124
125
134
135
145
234
235
245
345
1234
1235
1245
1345
2345
12345
*/
}
static void GetString(Dictionary<string,int> dd)
{
Dictionary<string, int> dic = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> kv in dd)
{
for (int i = kv.Value + 1; i < m_Data.Length; i++)
{
Console.WriteLine(kv.Key + m_Data[i]);
dic.Add(kv.Key + m_Data[i], i);
}
}
if(dic.Count>0) GetString(dic);
}
可以这样,从1到7循环,将数1转成二进制001,第三个是1,则取 {3},下面是所有组合:
1 001 {3}
2 010 {2}
3 011 {2,3}
4 100 {1}
5 101 {1,3}
6 110 {1,2}
7 111 {1,2,3} --------------------编程问答-------------------- 为何版主速度这么快 --------------------编程问答--------------------
这个在我博客里面有呢 --------------------编程问答-------------------- 提供一个二进制的思路:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Combo("123").ToList().ForEach(x => Console.WriteLine(x));
}
static IEnumerable<string> Combo(string s)
{
foreach (var x in (Enumerable.Range(1, Convert.ToInt32(Math.Pow((double)2, (double)s.Length)) - 1)))
{
string r = "";
var x1 = x;
for (int i = 0; i < s.Length; i++ )
{
r += x1 % 2 == 0 ? "" : s[i].ToString();
x1 /= 2;
}
yield return r;
}
}
}
}
补充:.NET技术 , C#