【问题标题】:Find all permutation of a string with certain position unchanged查找某个位置不变的字符串的所有排列
【发布时间】:2014-10-10 18:31:23
【问题描述】:

给定一串单词,说“OhMy”,保持大写字母固定(不变),但我们可以改变小写字母的位置。输出所有可能的排列。

例如。给定 "OhMy" 它应该输出 [ "OhMy", "OyMh"]

这就是我所做的:

    public static List<String> Permutation(String s){
    List<String> res = new ArrayList<String>();
    if (s == null || s.length() == 0){
        return res;
    }
    StringBuilder path = new StringBuilder(s);
    List<Character> candidates = new ArrayList<Character>();
    List<Integer> position = new ArrayList<Integer>();
    for (int i = 0; i < s.length(); i++){
        char c = s.charAt(i);
        if (Character.isAlphabetic(c) && Character.isLowerCase(c)){
            candidates.add(c);
            position.add(i);
        }
    }
    boolean[] occurred = new boolean[candidates.size()];
    helper(res, path, candidates, position, 0);
    return res;
}

public static void helper(List<String> res, StringBuilder path, List<Character> candidates, List<Integer> position, int index){
    if (index == position.size()){
        res.add(path.toString());
        return ;
    }
    for (int i = index; i < position.size(); i++){
        for (int j = 0; j < candidates.size(); j++){
            path.setCharAt(position.get(i), candidates.get(j));
            char c = candidates.remove(j);
            helper(res, path, candidates, position, index+1);
            candidates.add(j, c);
        }
    }
}

对于输入“Abc” 它将有结果 [Abc, Acb, Acc, Acb] 本质上,外循环迭代每个可能的位置,内循环在每个可能的位置尝试每个可能的候选。 我不知道为什么它有重复 li "Acc, Acb"

【问题讨论】:

  • 你有什么问题?

标签: algorithm recursion permutation depth-first-search backtracking


【解决方案1】:

您隐含问题的要点似乎是如何有效地枚举给定集合的所有排列,您可以在线阅读(有几种方法)。如果您可以枚举小写字母索引的所有排列,那么很容易进行簿记并将小写字母的每个排列与原始未更改的大写字母集合并,尊重大写字母的位置,所以你可以输出你的字符串。如果您在这部分遇到困难,请更新您的问题,应该有人可以帮助您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 2015-06-18
    • 1970-01-01
    • 2014-02-04
    • 2016-03-06
    • 1970-01-01
    • 2011-05-01
    • 2017-11-20
    相关资源
    最近更新 更多