C#回溯法,未测试。
public IList> MNCombination(int m, int n)
{
IList> result = new List> result();
combination(result, new List(), 0, m, n);
return result;
}
private void combination(IList> result, IList curLst, int
curSum, int m, int n) //m objects, n buckets
{
if(n == 0 && curSum == m) result.Add(new List(curLst));
else if (n > 0)
{
for(int i = curLst.Count == 0 ? 0 : curLst[curLst.Count - 1]; i +
curSum <= m; i++)
{
curLst.Add(i);
combination(result, curLst, curSum + i, m - i, n - 1);
curLst.RemoveAt(curLst.Count - 1);
}
}
}