剑指 Offer 38. 字符串的排列
  1BnnW8rtw7M9 2023年11月02日 58 0


剑指 Offer 38. 字符串的排列

方法一

class Solution {
    List<String> res = new ArrayList<>();
    boolean[] vis;

    public String[] permutation(String s) {
        vis = new boolean[s.length()];
        char[] ch = s.toCharArray();
        Arrays.sort(ch);
        backtrack(ch, new StringBuilder());
        return res.toArray(String[]::new);
    }

    void backtrack(char[] ch, StringBuilder path){
        if(path.length() == ch.length){
            res.add(path.toString());
            return;
        }

        for(int i = 0; i < ch.length; i++){
            if(i > 0 && ch[i] == ch[i - 1] && !vis[i - 1]) continue;
            if(vis[i]) continue;
            vis[i] = true;
            path.append(ch[i]);
            backtrack(ch, path);
            path.deleteCharAt(path.length() - 1);
            vis[i] = false;
        }
    }
}

方法二

哈希表去重

class Solution {
    List<String> res = new ArrayList<>();
    boolean[] vis;

    public String[] permutation(String s) {
        vis = new boolean[s.length()];
        char[] ch = s.toCharArray();
        Arrays.sort(ch);
        backtrack(ch, 0, "");
        return res.toArray(String[]::new);
    }

    void backtrack(char[] ch, int ind, String path){
        if(ind == ch.length){
            res.add(path);
            return;
        }

        HashSet<Character> set = new HashSet<>();
        for(int i = 0; i < ch.length; i++){
            if(vis[i] || set.contains(ch[i])) continue;
            set.add(ch[i]);
            // if(i > 0 && ch[i] == ch[i - 1] && !vis[i - 1]) continue;
            vis[i] = true;
            backtrack(ch, ind + 1, path + ch[i]);
            vis[i] = false;
        }
    }
}

方法三

交换

class Solution {
    List<String> res = new ArrayList<>();
    char[] c;

    public String[] permutation(String s) {
        c = s.toCharArray();
        dfs(0);
        return res.toArray(new String[0]);
    }

    void dfs(int x){
        if(x == c.length - 1){
            res.add(new String(c));
            return;
        }

        HashSet<Character> set = new HashSet<>();
        for(int i = x; i < c.length; i++){
            if(set.contains(c[i])) continue;
            set.add(c[i]);
            swap(i, x);
            dfs(x + 1);
            swap(i, x);
        }
    }

    void swap(int i, int x){
        char tmp = c[i];
        c[i] = c[x];
        c[x] = tmp;
    }
}


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
1BnnW8rtw7M9
作者其他文章 更多