题解 | #NC121 字符串的排列#

字符串的排列

http://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7

和力扣 剑指 Offer 38. 字符串的排列 相同

import java.util.*;
public class Solution {
    ArrayList<String> res = new ArrayList<>();
    public ArrayList<String> Permutation(String s) {
        char[] c = s.toCharArray();
        back(c, 0);
        return res;
    }
    
    public void back(char[] c, int idx) {
        if (idx == c.length - 1) {
            res.add(String.valueOf(c));     //字符数组转字符串
            return;
        }
        HashSet<Character> set = new HashSet<>();    //每个递归栈帧中都有一个独立的 set
        for (int i = idx; i < c.length; i++) {
            if (set.contains(c[i])) continue;
            set.add(c[i]);
            swap(c, idx, i);
            back(c, idx + 1);   //注意这里得是 idx + 1 而不是 i + 1
            swap(c, idx, i);
        }
    }

    public void swap(char[] c, int idx1, int idx2) {
        if (idx1 == idx2) return;
        char tmp = c[idx1];
        c[idx1] = c[idx2];
        c[idx2] = tmp;
    }
}
全部评论

相关推荐

04-11 23:51
门头沟学院 Java
坚定的芭乐反对画饼_许愿Offer版:人人都能过要面试干嘛,发个美团问卷填一下,明天来上班不就好了
点赞 评论 收藏
分享
04-25 18:13
五邑大学 Java
后来123321:大二两段实习太厉害了,我现在大二连面试都没有
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务