favorous 于 2014.12.15 00:50 提问

2个回答

devmiao      2014.12.15 02:02
``````using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int n = 13;
foreach (var item in Resolve(Fibonacci(n).ToArray(), new int[] { 0 }, n))
Console.WriteLine(string.Join(" + ", item.Select(x => x.ToString())) + " = " + n.ToString());
}

static IEnumerable<IEnumerable<int>> Resolve(IEnumerable<int> source, IEnumerable<int> cur, int seed)
{
if (seed == cur.Sum()) return new List<IEnumerable<int>> { cur.Where(x => x > 0) };
return source.Except(cur)
.Where(x => x + cur.Sum() <= seed && x > cur.Last())
.SelectMany(x => Resolve(source, cur.Concat(new int[] { x }), seed));
}

static IEnumerable<int> Fibonacci(int max)
{
int m = 1, n = 1;
yield return m;
while (n <= max)
{
yield return n;
n = n + m;
m = n - m;
}
}
}
}
``````

2 + 3 + 8 = 13
5 + 8 = 13
13 = 13
Press any key to continue . . .

devmiao      2014.12.15 02:04

1000的运行结果：
2 + 3 + 8 + 21 + 34 + 89 + 233 + 610 = 1000
2 + 3 + 8 + 55 + 89 + 233 + 610 = 1000
2 + 3 + 8 + 144 + 233 + 610 = 1000
2 + 3 + 8 + 377 + 610 = 1000
2 + 3 + 8 + 987 = 1000
5 + 8 + 21 + 34 + 89 + 233 + 610 = 1000
5 + 8 + 55 + 89 + 233 + 610 = 1000
5 + 8 + 144 + 233 + 610 = 1000
5 + 8 + 377 + 610 = 1000
5 + 8 + 987 = 1000
13 + 21 + 34 + 89 + 233 + 610 = 1000
13 + 55 + 89 + 233 + 610 = 1000
13 + 144 + 233 + 610 = 1000
13 + 377 + 610 = 1000
13 + 987 = 1000
Press any key to continue . . .