写一个函数,给定参数 x 指定一个数字 参数sum 指定和
要求:
1.求出和为sum的所有的可能的组合,以任意格式输出都可以
2.后一位不能大于前一位数(小于等于)
3.每一位大于0
eg: x为5 sum为17
那么 可能的结果有
5,5,5,2;
5,5,4,3;
5,5,3,3,1;
5,4,4,4;
……
4,4,4,4,1
……
2,2,2,2,2,2,2,2,1
……
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
等
题目的意思是 求出 <=X的数的 所有 和为 Sum
并按照 从大到小排列的序列
题目和例子对不上。这个从sum倒序,递归调用,及时判断是否大于sum和X,就可以了
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
static int[] d;
public static void Main()
{
var query = foo(new int[]{}, 1, 5, 17).Select(item => string.Join(",", item)).Distinct();
foreach (var item in query)
Console.WriteLine(item);
Console.WriteLine(query.Count());
}
static IEnumerable<IEnumerable<int>> foo(IEnumerable<int> seed, int n, int max, int sum)
{
if (seed.Sum() == sum)
{
yield return seed;
}
else
{
if (seed.Sum() < sum)
{
for (int i = n; i <= max; i++)
{
var items = foo(seed.Concat(new int[] { n }), i, max, sum);
foreach (var item in items) yield return item;
}
}
}
}
}
http://ideone.com/TpJYnq
在线编译,运行,101种
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2
1,1,1,1,1,1,1,1,1,1,1,1,1,1,3
1,1,1,1,1,1,1,1,1,1,1,1,1,2,2
1,1,1,1,1,1,1,1,1,1,1,1,1,4
1,1,1,1,1,1,1,1,1,1,1,1,2,3
1,1,1,1,1,1,1,1,1,1,1,1,5
1,1,1,1,1,1,1,1,1,1,1,2,2,2
1,1,1,1,1,1,1,1,1,1,1,2,4
1,1,1,1,1,1,1,1,1,1,1,3,3
1,1,1,1,1,1,1,1,1,1,2,2,3
1,1,1,1,1,1,1,1,1,1,2,5
1,1,1,1,1,1,1,1,1,1,3,4
1,1,1,1,1,1,1,1,1,2,2,2,2
1,1,1,1,1,1,1,1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,2,2,2,2,2,3
1,1,2,2,2,2,2,5
1,1,2,2,2,2,3,4
1,1,2,2,2,3,3,3
1,1,2,2,2,4,5
1,1,2,2,3,3,5
1,1,2,2,3,4,4
1,1,2,3,3,3,4
1,1,2,3,5,5
1,1,2,4,4,5
1,1,3,3,3,3,3
1,1,3,3,4,5
1,1,3,4,4,4
1,1,5,5,5
1,2,2,2,2,2,2,2,2
1,2,2,2,2,2,2,4
1,2,2,2,2,2,3,3
1,2,2,2,2,3,5
1,2,2,2,2,4,4
1,2,2,2,3,3,4
1,2,2,2,5,5
1,2,2,3,3,3,3
1,2,2,3,4,5
1,2,2,4,4,4
1,2,3,3,3,5
1,2,3,3,4,4
1,2,4,5,5
1,3,3,3,3,4
1,3,3,5,5
1,3,4,4,5
1,4,4,4,4
101
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
static int[] d;
public static void Main()
{
var query = foo(new int[]{}, 1, 5, 17 + 1).Select(item => string.Join(",", item.Skip(1))).Distinct();
foreach (var item in query)
Console.WriteLine(item);
Console.WriteLine(query.Count());
}
static IEnumerable<IEnumerable<int>> foo(IEnumerable<int> seed, int n, int max, int sum)
{
if (seed.Sum() == sum)
{
yield return seed;
}
else
{
if (seed.Sum() < sum)
{
for (int i = n; i <= max; i++)
{
var items = foo(seed.Concat(new int[] { n }), i, max, sum);
foreach (var item in items) yield return item;
}
}
}
}
}
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2
1,1,1,1,1,1,1,1,1,1,1,1,1,1,3
1,1,1,1,1,1,1,1,1,1,1,1,1,2,2
1,1,1,1,1,1,1,1,1,1,1,1,1,4
1,1,1,1,1,1,1,1,1,1,1,1,2,3
1,1,1,1,1,1,1,1,1,1,1,1,5
1,1,1,1,1,1,1,1,1,1,1,2,2,2
1,1,1,1,1,1,1,1,1,1,1,2,4
1,1,1,1,1,1,1,1,1,1,1,3,3
1,1,1,1,1,1,1,1,1,1,2,2,3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