组合数学:生成所有"国家" - 排列组合组合、排列组合、数学、国家

2023-09-11 22:38:29 作者:迷恋黑夜带给自己的孤独感

我有一个整数数组: N []

另外,我有一个数组(上午十时正[] )包含 n.length 整数。我需要生成的所有组合N [] 以下列方式:

Also, I have an array (Nr[]) contains n.length integers. I need to generate all combinations of n[] in a following way:

/* let n.length == 3 and Nr[0] = 2, Nr[1] = 3, Nr[2] = 3 */
n = {0, 0, 0};
n = {1, 0, 0};
n = {2, 0, 0};
n = {0, 1, 0};
n = {0, 2, 0};
n = {0, 3, 0};
n = {0, 0, 1};
...
n = {1, 1, 0};
n = {1, 2, 0};
n = {1, 3, 0};
n = {2, 1, 0};
n = {2, 2, 0};
n = {2, 3, 0};
n = {1, 1, 1};
...
n = {0, 1, 1};
// many others

我们的目标是要找到 N ,其中 N [I] 可 0号[i] 。

我没有成功......如何解决它的Java?或者没有在Java中...

I did not succeed... How to solve it in Java? Or not in Java...

推荐答案

您可能需要使用递归,尝试所有对每个指标的可能性,和与递归调用子阵,无的最后一个元素。

You might want to use recursion, try all possibilities for each index, and recursively invoke with the subarray, "without" the last element.

public static void printPermutations(int[] n, int[] Nr, int idx) {
    if (idx == n.length) {  //stop condition for the recursion [base clause]
        System.out.println(Arrays.toString(n));
        return;
    }
    for (int i = 0; i <= Nr[idx]; i++) { 
        n[idx] = i;
        printPermutations(n, Nr, idx+1); //recursive invokation, for next elements
    }
}

调用与

public static void main(String[] args) {
    /* let n.length == 3 and Nr[0] = 2, Nr[1] = 3, Nr[2] = 3 */
    int[] n = new int[3];
    int Nr[] = {2,3,3 };
    printPermutations(n, Nr, 0);
}

将让你:

[0, 0, 0]
[0, 0, 1]
[0, 0, 2]
[0, 0, 3]
[0, 1, 0]
[0, 1, 1]
[0, 1, 2]
[0, 1, 3]
[0, 2, 0]
[0, 2, 1]
[0, 2, 2]
[0, 2, 3]
[0, 3, 0]
[0, 3, 1]
[0, 3, 2]
[0, 3, 3]
[1, 0, 0]
[1, 0, 1]
[1, 0, 2]
[1, 0, 3]
[1, 1, 0]
[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 2, 0]
[1, 2, 1]
[1, 2, 2]
[1, 2, 3]
[1, 3, 0]
[1, 3, 1]
[1, 3, 2]
[1, 3, 3]
[2, 0, 0]
[2, 0, 1]
[2, 0, 2]
[2, 0, 3]
[2, 1, 0]
[2, 1, 1]
[2, 1, 2]
[2, 1, 3]
[2, 2, 0]
[2, 2, 1]
[2, 2, 2]
[2, 2, 3]
[2, 3, 0]
[2, 3, 1]
[2, 3, 2]
[2, 3, 3]

不过请注意 - 在使用这种方法可以打印的所有元素为你介绍,但在不同的顺序,然后您的例子

Note however - that using this method does print all elements as you describes, but in a different order then your example.