java - 顺序排列?

标签 java

我有特定数量的数字。现在我想以某种方式显示此序列的所有可能排列。

比如数字的数量是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/

相关文章:

java - 如何在 Android Studio 中保持方法折叠?

java - 将 ImageView 作为 mask 应用到另一个 ImageView

java - Swing 加速器

java - 在 JOptionPane.showMessageDialog 上应用外观

java - 如果接口(interface)有两个同名的方法,那么在实现时首先调用哪个方法?

java - 抽象 Activity 导致 findViewById() 不起作用

java - 调用休息 Web 服务时出错

java - 如何将Tomcat环境变量设置为系统环境属性?

java - 类路径问题 - getJNIEnv 失败

java.lang.UnsatisfiedLinkError : No implementation found due to Library not loading 错误