背景:
C# 1到10的数组每次取三个不能重复,有多少种组合?{1,2,3,4,5,6,7,8,9,10}
比如1,2,3 1,2,4 1,2,5 等
求算法输出,,给出如下 已验证
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Int32[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
String[] list = GetAllCombination(arr, 2);
foreach (String s in list)
Console.WriteLine(s);
Console.WriteLine("组合总数:" + list.Length);
}
public static String[] GetAllCombination(Int32[] arr, Int32 n) //取n个的组合
{
Int32[] state = new Int32[arr.Length];
List<String> list = new List<String>();
for (Int32 i = 0; i < n; i++)
{
state[i] = 1;
}
for (Int32 i = n; i < state.Length; i++)
{
state[i] = 0;
}
String str = "";
for (Int32 i = 0; i < n; i++)
str += arr[i] + ",";
list.Add(str.TrimEnd(','));
while (true)
{
Boolean flag = true;
Int32 index = 0;
Int32 oneCount = 0;
Int32 zeroCount = 0;
StringBuilder sbuilder = new StringBuilder();
for (; index < state.Length - 1; index++)
{
if (state[index] == 1 && state[index + 1] == 0)
{
Int32 temp = state[index];
state[index] = state[index + 1];
state[index + 1] = temp;
break;
}
}
for (Int32 i = 0; i < index; i++)
{
if (state[i] == 0)
zeroCount++;
else
oneCount++;
}
for (Int32 i = 0; i < index; i++)
{
if (i < oneCount)
state[i] = 1;
else
state[i] = 0;
}
for (Int32 i = 0; i < arr.Length; i++)
{
if (state[i] == 1)
sbuilder.Append(arr[i] + ",");
}
list.Add(sbuilder.ToString().TrimEnd(','));
for (Int32 i = 0; i < arr.Length - n; i++)
{
if (state[i] == 1)
{
flag = false;
break;
}
}
if (flag)
break;
}
return list.ToArray();
}
}
}