fork download
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4.  
  5. public class Test
  6. {
  7. static int[] d;
  8. public static void Main()
  9. {
  10. int m = 5;
  11. var query = foo(new int[]{ }, m).Select(item => string.Join("+", item)).Distinct();
  12. foreach (var item in query)
  13. Console.WriteLine(item);
  14. Console.WriteLine(query.Count());
  15. }
  16. static IEnumerable<IEnumerable<int>> foo(IEnumerable<int> seed, int m)
  17. {
  18. if (seed.Sum() == m)
  19. {
  20. yield return seed;
  21. }
  22. else
  23. {
  24. if (seed.Count() == 0)
  25. {
  26. for (int i = 1; i <= m; i++)
  27. {
  28. var items = foo(seed.Concat(new int[] { i }), m);
  29. foreach (var item in items) yield return item;
  30. }
  31. }
  32. else
  33. {
  34. if (seed.Sum() < m)
  35. {
  36. for (int i = seed.Last(); i <= m; i++)
  37. {
  38. var items = foo(seed.Concat(new int[] { i }), m);
  39. foreach (var item in items) yield return item;
  40. }
  41. }
  42. }
  43. }
  44. }
  45.  
  46. }
Success #stdin #stdout 0.06s 24200KB
stdin
Standard input is empty
stdout
1+1+1+1+1
1+1+1+2
1+1+3
1+2+2
1+4
2+3
5
7