在Java

时间:2017-07-06 12:33:56

标签: java arrays integer permutation

给定一个大小为n的数组,生成并打印数组中r元素的所有可能排列。

例如,如果n为4,输入数组为[0,1,2,3],r为3,则输出应为

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

输入数组中的所有元素都是整数,从0到n-1。如何使用Java打印所有可能的排列?

重要提示:单个排列中所有元素的数量并不总是原始数组的大小。它小于或等于原始数组的大小。此外,每个排列中元素的顺序都很重要。

当n = 4且r = 3时,我写了一些代码。如果n = 100且r = 50,我的代码将非常难看。当参数只有n和r?

时,有没有聪明的方法可以做到这一点
public static void main(String[] args) {

    // original array
    ArrayList < Integer > items = new ArrayList < > ();

    // all permutations
    ArrayList < ArrayList < Integer >> allPermutations = new ArrayList < ArrayList < Integer >> ();

    // define the end item of the original array.
    // this is n, suppose it's 4 now.
    int endItem = 4;
    for (int i = 0; i < endItem; i++) {
        items.add(i);
    }


    // r means how many elements in each single permutation
    // suppose it's 3 now, i have to write for-loop three times
    // if r is 100, i have to write for-loop 100 times

    // first of the "r"
    for (int i = 0; i < items.size(); i++) {
        // second of the "r"
        for (int j = 0; j < items.size(); j++) {
            // can't be identical to i
            if (j == i)
                continue;

            // third of the "r"
            for (int k = 0; k < items.size(); k++) {
                // can't be identical to i or j
                if (k == i || k == j)
                    continue;

                // a single permutation
                ArrayList < Integer > singlePermutation = new ArrayList < > ();
                singlePermutation.add(items.get(i));
                singlePermutation.add(items.get(j));
                singlePermutation.add(items.get(k));

                // all permutations
                allPermutations.add(singlePermutation);

            }
        }
    }
    for (ArrayList < Integer > permutation: allPermutations) {
        System.out.println(permutation);
    }
    System.out.println(allPermutations.size());

}

1 个答案:

答案 0 :(得分:1)

将解决方案从问题转移到答案:

  

<强>解决方案:

     

感谢older coder,我找到了解决方案。

volttron -vv -l volttron.log > /dev/null 2>&1&