从1..n中间选取任意组合,其和为m,列出所有组合的算法。
2010-11-30 11:00 java线程例子 阅读(284) 评论(0) 编辑 收藏 举报采用递推方法,并将每次的结果保存,并做为下一个的计算的基础。
/// <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";
}
}