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

本文介绍了一种使用递推方法来找出所有可能的整数组合,这些组合的元素范围从1到n,且组合之和等于给定值m。通过递归地构建解集并利用之前计算的结果来提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

/// <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";
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值