从1..n中间选取任意组合,其和为m,列出所有组合的算法。

        采用递推方法,并将每次的结果保存,并做为下一个的计算的基础。

        ///


        /// 从1..n中间选取任意组合,其和为m
        ///

        ///
        ///
        private void ListComboDigit(int n, int m)
        {
            //显示n*(n+1)小于2*m则无解
            if (n * (n + 1) < 2 * m)
                return;
            int iItems = 0;
            List>> theRets = new List>>();
            for (int i = 1; i <= m; i++)
            {
                List> theCurrRets = new List>();
                for (var k = 1; k <= i - 1; k++)
                {
                    int tmp = i - k;
                    if (tmp > 0 && tmp <= n)
                    {
                        foreach (var item in theRets[k - 1])
                        {
                            if (tmp > item[item.Count - 1])
                            {
                                List theTmp = new List();
                                theTmp.AddRange(item);
                                theTmp.Add(tmp);
                                theCurrRets.Add(theTmp);
                            }
                            iItems++;
                        }
                    }
                   
                }
                if (i <= n)
                {
                    List theSelf = new List();
                    theSelf.Add(i);
                    theCurrRets.Add(theSelf);  
                }
                iItems++;
                theRets.Add(theCurrRets);
            }
            this.richTextBox1.Text = "";

            foreach (var item in theRets[m - 1])
            {
                string tmpstr = "";
                foreach (var it in item)
                {
                    tmpstr += it.ToString() + " ";
                }
                this.richTextBox1.Text += tmpstr + "/r/n";
            }

        }

你可能感兴趣的:(1,C#)