gold-8-8


有重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合。

示例1:

输入:S = "qqe"
输出:["eqq","qeq","qqe"]

示例2:

输入:S = "ab"
输出:["ab", "ba"]

提示:

  1. 字符都是英文字母。
  2. 字符串长度在[1, 9]之间。
import java.util.HashSet;

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public String[] permutation(String S) {
        if (S == null || S.length() == 0) {
            return new String[0];
        }

        List<String> result = new ArrayList<>();
        Set<Integer> indexSet = new HashSet<>();
        doPermute(result, "", indexSet, S);
        return result.toArray(new String[result.size()]);
    }

    private void doPermute(List<String> result, String curS, Set<Integer> indexSet, String S) {
        if (curS.length() == S.length()) {
            if (!result.contains(curS)) {
                result.add(new String(curS));
            }
            return;
        }

        for (int i = 0; i < S.length(); i++) {
            if (!indexSet.contains(i)) {
                indexSet.add(i);
                doPermute(result, curS + S.charAt(i), indexSet, S);
                indexSet.remove(i);
            }
        }
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !