LeetCode 剑指 Offer 38. 字符串的排列

题目描述

输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof

Java代码

class Solution {
    List<String> res = new LinkedList<>();

    char[] c;

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

    void DFS(int x) {
        if(x == c.length - 1){
            res.add(String.valueOf(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(x, i);
            DFS(x + 1);
            swap(x, i);
        }
    }
    void swap(int x1, int x2){
        char t = c[x1];
        c[x1] = c[x2];
        c[x2] = t;
    }
}
posted @ 2021-07-19 16:45  子丶非鱼Zzz  阅读(39)  评论(0)    收藏  举报