【劍指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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章