X的所有可能的组合分成N个书库组合、书库

2023-09-11 05:37:11 作者:蝶醉月倾城

我相信这个问题有一个正式的名字,并且知道这个名字可能会帮我找到了解决办法,但我不知道它,和措辞问题对谷歌一直指着我到的背包问题,这是不一样的东西。

I am sure this problem has a formal name, and knowing that name would probably help me find the solution, but I don't know it, and wording the problem for Google keeps pointing me to the Knapsack Problem, which isn't the same thing.

我想采取一些值X,并找到分裂的每一个可能的组合,重视到整个整数N个堆栈。

I want to take some value X and find every possible combination of splitting that value into N stacks of whole integers.

在情况下我的措辞是混乱的,这里是X的例子= 4,N = 3

In case my wording is confusing, here is an example of X = 4, N = 3

Stack -> 1 | 2 | 3 |
----------------------
#1-----> 4 | 0 | 0 |
----------------------
#2-----> 3 | 1 | 0 |
----------------------
#3-----> 2 | 1 | 1 |
----------------------
#4-----> 2 | 2 | 0 |

复制是可以接受的,因为它很容易除去,但最好它不会被计算。算法解决该问题将是完美的,但即使发现出了问题有一个名字会使研究更容易。谢谢你。

Duplication is acceptable, since its easy to remove, but ideally it would not be calculated. An algorithm for solving the problem would be perfect, but even finding out of the problem has a name would make research easier. Thanks.

推荐答案

这是在C#中user434507的回答是:

This is user434507's answer in C#:

class Program
{
    static void Main(string[] args)
    {
        var v = Partitions(5, 3, 5);

        for (int i = 0; i < v.Count; i++)
        {
            for (int x = 0; x < v[i].Count; x++)
                Console.Write(v[i][x] + " "); 
            Console.WriteLine();
        }
    }

    static private List<List<int>> Partitions(int total, int stacks, int max)
    {
        List<List<int>> partitions = new List<List<int>>();

        if (total <= 1 || stacks == 1)
        {
            if (total <= max)
            {
                partitions.Add(new List<int>());
                partitions[0].Add(total);
            }

            return partitions;
        }
        for (int y = Math.Min(total, max); y >= 1; y--)
        {
            var w = Partitions(total - y, stacks - 1, y);
            for (int i = 0; i < w.Count; i++)
            {
                w[i].Add(y);
                partitions.Add(w[i]);
            }
        }

        return partitions;
    }
}