在Java中查找数组中每个可能的元素组合

时间:2017-02-20 20:06:52

标签: java arrays combinations

假设我有这个数组: [a,b,c,d] 我如何找到所有可能的组合,即 ab,abc,abcd .....等。 这需要包含重复项,因此 abcd dcba 不同 目的是找到所有组合并检查是否可以从不同的阵列进行相同的组合。我最初的尝试是:

for (int i = 0; i < values.length; i++) {
        String cur = values[i];

        for (int k = 0; k < values.length; k++) {
            if (i != k) {
                cur = cur.concat(values[k]);
                System.out.println(cur);
            }

        }
    }

给出了输出:

ab
abc
abcd
ba
bac
bacd
ca
cab
cabd
da
dab
dabc

显然不正确

这是针对我尝试改进的编程挑战,因此任何有关更快解决方案的建议都会有所帮助

1 个答案:

答案 0 :(得分:0)

这是你正在寻找的吗?

public static void main(String[] data) {
    ArrayList<Character> chars = new ArrayList<>(4);
    chars.add('a');
    chars.add('b');
    chars.add('c');
    chars.add('d');
    System.out.println(getPermutations("", chars));

}

private static ArrayList<String> getPermutations(String currentResult, ArrayList<Character> possibleChars) {
    ArrayList<String> result = new ArrayList<>(possibleChars.size());
    for (char append: possibleChars) {
        String permutation = currentResult + append; //create a new string with an additional character
        result.add(permutation); //add the permutation to the result
        if (possibleChars.size() > 0) {
            //make a new list with the appendable characters
            ArrayList<Character> possibleCharsUpdated = (ArrayList)possibleChars.clone();
            //from that list, exclude the character we just appended
            possibleCharsUpdated.remove(new Character(append));
            //merge the result of a recursive call of this method and the result we already had
            result.addAll(getPermutations(permutation, possibleCharsUpdated));
        }
    }
    return result;
}
相关问题