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

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

        /// <summary>
        /// 从1..n中间选取任意组合,其和为m
        /// </summary>
        /// <param name="n"></param>
        /// <param name="m"></param>
        private void ListComboDigit(int n, int m)
        {
            //显示n*(n+1)小于2*m则无解
            if (n * (n + 1) < 2 * m)
                return;
            int iItems = 0;
            List<List<List<int>>> theRets = new List<List<List<int>>>();
            for (int i = 1; i <= m; i++)
            {
                List<List<int>> theCurrRets = new List<List<int>>();
                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<int> theTmp = new List<int>();
                                theTmp.AddRange(item);
                                theTmp.Add(tmp);
                                theCurrRets.Add(theTmp);
                            }
                            iItems++;
                        }
                    }
                   
                }
                if (i <= n)
                {
                    List<int> theSelf = new List<int>();
                    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";
            }

        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值