Finding all numbers that sum to a specified target number (integer partition)

前端 未结 1 1959
时光取名叫无心
时光取名叫无心 2021-01-07 00:22

First i want to say i\'m still learning so my programming skills are not very good, and i\'m willing to accept any advice you have. Second i\'m still learning english so

相关标签:
1条回答
  • 2021-01-07 00:59

    Here's one approach that first builds the combinations into a tree structure, then arranges them into lists of ints:

    internal class Combination
    {
        internal int Num;
        internal IEnumerable<Combination> Combinations;
    }
    
    internal static IEnumerable<Combination> GetCombinationTrees(int num, int max)
    {
        return Enumerable.Range(1, num)
                         .Where(n => n <= max)
                         .Select(n =>
                             new Combination
                             {
                                 Num = n,
                                 Combinations = GetCombinationTrees(num - n, n)
                             });
    }
    
    internal static IEnumerable<IEnumerable<int>> BuildCombinations(
                                                   IEnumerable<Combination> combinations)
    {
        if (combinations.Count() == 0)
        {
            return new[] { new int[0] };
        }
        else
        {
            return combinations.SelectMany(c =>
                                  BuildCombinations(c.Combinations)
                                       .Select(l => new[] { c.Num }.Concat(l))
                                );
        }
    }
    
    public static IEnumerable<IEnumerable<int>> GetCombinations(int num)
    {
        var combinationsList = GetCombinationTrees(num, num);
    
        return BuildCombinations(combinationsList);
    }
    
    public static void PrintCombinations(int num)
    {
        var allCombinations = GetCombinations(num);
        foreach (var c in allCombinations)
        {
            Console.WriteLine(string.Join(", ", c));
        }
    }
    

    When run with the input value 6, this produces:

    1, 1, 1, 1, 1, 1
    2, 1, 1, 1, 1
    2, 2, 1, 1
    2, 2, 2
    3, 1, 1, 1
    3, 2, 1
    3, 3
    4, 1, 1
    4, 2
    5, 1
    6
    
    0 讨论(0)
提交回复
热议问题