0

I need to generate permutations over a set of integers.

However the placement of the numbers matter.

In position 0, the range is from 0-2. In position 1, the range is from 0-3. In position 2, the range is from 0-1.

So the answer would be:

000 001 010 011 020 021 030 031

100 101 110 111 120 121 130 131

200 201 210 211 220 221 230 231

4

1 回答 1

1

执行以下操作:

public class Test {

    public static void main(String[] args) {
        Test x = new Test();
        x.generatePermutations(2, 3, 1);
    }

    private void generatePermutations(int intervalOne, int intervalTwo,
            int intervalThree) {
        for (int i = 0; i <= intervalOne; i++) {
            for (int j = 0; j <= intervalTwo; j++) {
                for (int k = 0; k <= intervalThree; k++) {
                    System.out.print(i + "" + j + "" + k + " ");
                }
            }
        }
    }
}

编辑:我认为这会做一个任意数量的间隔数组:(你必须检查它的正确性:

public class Test {

    public static void main(String[] args) {
        Test x = new Test();
        int[] intervals = { 1, 1, 1, 1, 1 };
        x.generatePermutations(intervals);
    }

    private void generatePermutations(int[] intervals) {
        generatePermutations(intervals, 0, "");
    }

    private void generatePermutations(int[] intervals, int intpos,
            String lastPerm) {

        if (intpos == intervals.length)
            return;

        for (int i = 0; i <= intervals[intpos]; i++) {
            if (intpos == intervals.length - 1) {
                System.out.print(lastPerm + i + " ");
            }
            generatePermutations(intervals, intpos + 1, lastPerm + i);
        }
    }
}
于 2013-05-05T23:54:58.080 回答