Algorithm to determine possible groups of items

后端 未结 6 1736
遥遥无期
遥遥无期 2021-02-03 11:51

I am scratching my head trying to do this and it\'s eating me up. I know it is not THAT complex. I have a number of items, this number can be equal or greater than three. Then I

6条回答
  •  遥遥无期
    2021-02-03 12:33

    In pseudocode:

    List results;
    
    void YourAnswer(int n) {
        GeneratePossiblities("", [3, 4, 5, 6, 7], n);
    }
    
    void GeneratePossibilities(String partialResult, List buildingBlocks, int n) {
        if (n == 0) {
            // We have a solution
            results.Add(partialResult);
        } else if (buildingBlocks.IsEmpty()) {
            // Dead-end: there is no solution that starts with the partial result we have and contains only the remaining building blocks
            return;
        } else {
            int first = buildingBlocks.First();
            buildingBlocks.PopFirst();
            for (int i = 0, i < n/first; i++) {
              GeneratePossibilities(partialResult + " " + i + "groups of " + first,
                                    buildingBlocks, 
                                    n - i * first);
            }
        }
    }
    

    The first two cases are pretty straight-forward. The third one, you figure out (for example) how many groups of size 3 there are - that can be any number between 0 and n/3, and then recursively the function with [4, 5, 6, 7], etc.

提交回复
热议问题