我有特定数量的数字。现在我想以某种方式显示此序列的所有可能排列。
比如数字的数量是3,我要显示:
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
1 0 0
1 0 1
1 0 2
1 1 0
1 1 1
1 1 2
1 2 0
1 2 1
1 2 2
2 0 0
2 0 1
2 0 2
2 1 0
2 1 1
2 2 0
2 2 1
2 2 2
我有这段代码可以做到这一点,其中深度是数字的数量。显然这段代码不能正常工作。任何提示如何改进?:
for (int i = 0; i < (depth * depth); i++) {
path = setPath(depth, path, i);
print(path);
}
private static int[] setPath(int depth, int[] path, int i) {
for (int j = 1; j <= depth; j++) {
if (j == 1) {
path[depth-1] = i%depth;
} else {
path[depth-j] = i / ((j-1)*depth);
}
}
return path;
}
最佳答案
这是一些代码:
public static void main(String[] args) throws IOException {
List<Number> list = new ArrayList<Number>();
list.add(0);
list.add(1);
list.add(2);
printCombinations(new ArrayList<Number>(), list, 0);
}
public static void printCombinations(List<Number> done, List<Number> numbers, int depth) {
if (numbers.size() <= depth) {
System.out.println(done); // replace with something better
} else {
for (Number r : numbers) {
List<Number> newDone = new ArrayList<Number>(done);
newDone.add(r);
printCombinations(newDone, numbers, depth + 1);
}
}
}
对于任意数量的任意数字,准确打印您所要求的内容。 :)
关于java - 顺序排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5790679/