【剑指offer】38.字符串的排列

38.字符串的排列

面试题38. 字符串的排列

难度中等38

输入一个字符串,打印出该字符串中字符的所有排列。

你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。

示例:

输入:s = "abc"
输出:["abc","acb","bac","bca","cab","cba"]

回溯

//dfs  time :O(N!)  space  : O(N^2)
    List<String> ret = new LinkedList<>();
    char [] ch;
    public String[] permutation(String s) {
        if(s == null){
            return new String[0];
        }
        ch = s.toCharArray();
        dfs(0);
        return ret.toArray(new String[ret.size()]);
    }

    private void dfs(int x){
        //终止条件
        if(x == ch.length-1){
            ret.add(String.valueOf(ch));
            return;
        }
        HashSet<Character> hashSet = new HashSet<>();
        
        for(int i=x;i<ch.length;i++){
            //去重 -》剪枝操作
            if(hashSet.contains(ch[i]))  continue;
            hashSet.add(ch[i]);
            //交换
            swap(i,x);
            dfs(x+1);
            //撤回交换
            swap(x,i);
        }
    }

    private void swap(int x,int i){
        char tmp = ch[x];
        ch[x] = ch[i];
        ch[i] = tmp;
    }
原文地址:https://www.cnblogs.com/qxlxi/p/12860602.html