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

///

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

}

}

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐