将排列写入ArrayList

时间:2015-01-01 21:52:40

标签: java algorithm

我正在尝试置换字符串并将所有排列复制到ArrayList。但我得到一个无限循环,我没有看到在哪里。有什么帮助吗?

private static List<String> permute(String str) {
    List<String> permutations = new ArrayList<String>();
    return permuteHelper("", str, permutations);
}

private static List<String> permuteHelper(String prefix, String str, List<String> permutations) {
    int length = str.length();

    if (length == 0) {
        permutations.add(prefix);
    } else {
        for (int i = 0; i < length; i++) {
            permuteHelper(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, length), permutations);
        }
    }
    return permutations;
}

0 个答案:

没有答案