我怎样才能更好地做到最大化性能和效率(for loop)

时间:2015-06-29 16:03:41

标签: java nested-loops

我有这些嵌套的for循环,有什么方法可以让它更有效率吗?

我想要这些数字的每一个组合。例如。 2,290,29091993..etc 组合只是一个String Arraylist。

int[] combo = new int[]{2, 9, 0, 9, 1, 9, 9, 3};
for (int i = 0; i < combo.length; i++) {
    combinations.add(combo[i] + "");
    for (int x = 0; x < combo.length; x++) {
        combinations.add(combo[i] + "" + combo[x]);
        for (int y = 0; y < combo.length; y++) {
            combinations.add(combo[i] + "" + combo[x] + "" + combo[y]);
            for (int z = 0; z < combo.length; z++) {
                combinations.add(combo[i] + "" + combo[x] + "" + combo[y] + "" + combo[z]);
                for (int z1 = 0; z1 < combo.length; z1++) {
                    combinations.add(combo[i] + "" + combo[x] + "" + combo[y] + "" + combo[z] + "" + combo[z1]);
                    for (int z2 = 0; z2 < combo.length; z2++) {
                        combinations.add(combo[i] + "" + combo[x] + "" + combo[y] + "" + combo[z] + "" + combo[z1] + "" + combo[z2]);
                        for (int z3 = 0; z3 < combo.length; z3++) {
                            combinations.add(combo[i] + "" + combo[x] + "" + combo[y] + "" + combo[z] + "" + combo[z1] + "" + combo[z3]);
                        }
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

void addPermutation(List<String> combinations, int level, int[] combo,
        StringBuilder buffer) {
    int length = 0;
    if (buffer != null) {
        length = buffer.length();
    } else {
        buffer = new StringBuilder();
    }
    if (level < combo.length) {
        for (int x : combo) {
            buffer.append(Integer.valueOf(x));
            String current = buffer.toString();
            //System.out.println(current); XXX for debug purpose
            combinations.add(current);
            addPermutation(combinations,level+1,combo,buffer);
            buffer.setLength(length);
        }
    }
}

@Test
public void testPermutation(){
    List<String> combinations = new LinkedList<String>();
    int[] combo = new int[]{2, 9, 0};
    addPermutation(combinations, 0, combo, null);
}

因为它的时间复杂性很高,所以它很难实现奇迹。