111,126
社区成员
发帖
与我相关
我的任务
分享
static void Main(string[] args)
{
ShowResult();
}
public static void ShowResult()
{
string str = "1,2,3";
string[] temp1 = str.Split(',');
List<string> list = new List<string>();
foreach (string s in temp1)
{
if (list.Count == 0)
list.AddRange(temp1);
else
list.AddRange(JoinPart(list, s));
}
foreach (string s in list)
Console.WriteLine(s);
}
public static List<string> JoinPart(List<string> part1, string s)
{
List<string> result = new List<string>();
foreach (string str1 in part1)
{
result.Add(str1 + s);
}
return result;
}
/*
1
2
3
12
22
32
13
23
33
123
223
323
*/
//-----------------------------------------------------------------------------
//
// 算法:排列组合类
//
// 版权所有(C) Snowdust
// 个人博客 http://blog.csdn.net/snowdust & http://snowdust.cnblogs.com
// MSN & Email snowdust77@sina.com
//
// 此源代码可免费用于各类软件(含商业软件)
// 允许对此代码的进一步修改与开发
// 但必须完整保留此版权信息
//
//-----------------------------------------------------------------------------
/// <summary>
/// 递归算法求数组的组合(私有成员)
/// </summary>
/// <param name="list">返回的范型</param>
/// <param name="t">所求数组</param>
/// <param name="n">辅助变量</param>
/// <param name="m">辅助变量</param>
/// <param name="b">辅助数组</param>
/// <param name="M">辅助变量M</param>
private static void GetCombination<T>(ref List<T[]> list, T[] t, int n, int m, int[] b, int M)
{
for (int i = n; i >= m; i--)
{
b[m - 1] = i - 1;
if (m > 1)
{
GetCombination(ref list, t, i - 1, m - 1, b, M);
}
else
{
if (list == null)
{
list = new List<T[]>();
}
T[] temp = new T[M];
for (int j = 0; j < b.Length; j++)
{
temp[j] = t[b[j]];
}
list.Add(temp);
}
}
}
/// <summary>
/// 求数组中n个元素的组合
/// </summary>
/// <param name="t">所求数组</param>
/// <param name="n">元素个数</param>
/// <returns>数组中n个元素的组合的范型</returns>
public static List<T[]> GetCombination<T>(T[] t, int n)
{
if (t.Length < n)
{
return null;
}
int[] temp = new int[n];
List<T[]> list = new List<T[]>();
GetCombination(ref list, t, t.Length, n, temp, n);
return list;
}
int[] arr = {1,2,3};
List<int[]> result = new List<int[]>();
for(int i = 0; i < arr.Length; i++)
{
result.AddRange(GetCombination(arr, i+1));
}
// 输出
foreach(int[] varr in result)
{
foreach(int vnum in varr)
{
Console.Write(vnum.ToString() + " ");
}
Console.WriteLine("");
}
/*
3
2
1
2 3
1 3
1 2
1 2 3
*/
public static List<List<T>> GetCombination<T>(T[] t)
{
List<List<T>> result = new List<List<T>>();
int length = t.Length;
int num = (int)Math.Pow(2, length) - 1;
for (int i = 1; i <= num; i++)
{
List<T> tmp = new List<T>();
for (int j = 0; j < length; j++)
{
if ((i >> j) % 2 == 1)
tmp.Add(t[j]);
}
result.Add(tmp);
}
return result;
}
static void Main(string[] args)
{
int[] arr = { 1, 2, 3 };
List<List<int>> result = GetCombination(arr);
foreach (List<int> varr in result)
{
foreach (int vnum in varr)
{
Console.Write(vnum.ToString() + " ");
}
}
}
/*
输出
1
2
1 2
3
1 3
2 3
1 2 3
*/