字符串的排列——leetcode38

字符串的排列

题目:字符串的排列

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

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

示例:

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

题解:回溯

class Solution {
    List<String> results;
    public void dfs(char[] s, int[] book, StringBuilder sb) {
        if(sb.length()==s.length) {
            results.add(sb.toString());
            return;
        }
        for(int i=0;i<s.length;i++) {
            if(book[i]==1) continue;
            if(i>0 && s[i]==s[i-1] && book[i-1]==0) continue;
            book[i]=1;
            sb.append(s[i]);
            dfs(s, book, sb);
            sb.deleteCharAt(sb.length()-1);
            book[i]=0;
        }
    }
    public String[] permutation(String s) {
        results=new ArrayList<>();
        int book[]=new int[s.length()];
        char[] cs=s.toCharArray();
        Arrays.sort(cs);

        dfs(cs, book, new StringBuilder());
        return results.toArray(new String[0]);
    }
}

 

posted @ 2022-01-16 21:12  言思宁  阅读(22)  评论(0编辑  收藏  举报