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

     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();
                }
            }
        }


from clipboard

玩咖指针 2022-06-03 23:24:29