N个数随机相加得出固定值的排列组合

时间:2021-09-10 16:35:04
     static double[] iArr = new double[10] { 1,2,3,4,5,6,7,8,9,10 };
static Stack<double> stack = new Stack<double>();
static double tempNum = 0;
static double a = 11; static void Main(string[] args)
{
for (int i = 0; i < iArr.Length; i++)
{
if (iArr[i] == a)
{
continue;
}
if (iArr[i] > a)
{
continue;
}
stack.Clear();
stack.Push(iArr[i]);
Func(i, a - iArr[i]);
}
} private static void Func(int i, double iValue)
{
for (int j = i + 1; j < iArr.Length; j++)
{
if (iArr[j] > iValue)
{
continue;
}
else if (iValue == iArr[j])
{
stack.Push(iArr[j]);
foreach (int ss in stack)
{
Console.Write(ss+"+");
tempNum += ss;
if (tempNum == a)
{
Console.WriteLine();
tempNum = 0;
}
}
stack.Pop();
}
else if (iValue > iArr[j])
{
stack.Push(iArr[j]);
Func(j, iValue - iArr[j]);
stack.Pop();
}
}
}

  N个数随机相加得出固定值的排列组合

注:借鉴别人的方法,希望能有更优的方法计算