LeetCode—剑指Offer:字符串的排列(回溯)

字符串的排列(中等)

2020年9月3日

题目来源:力扣

在这里插入图片描述
解题
进行循环,每进一次遍历进行两两交换,遍历完后回溯

class Solution {
    
    
    //定义结果列表
    List<String> res=new ArrayList<>();
    //字符数组
    char[] c;
    public String[] permutation(String s) {
    
    
        //把字符串转为字符数组
        c=s.toCharArray();
        //做深度遍历
        dfs(0);
        return res.toArray(new String[0]);
    }
    private void dfs(int x){
    
    
        //如果传入数字与字符数组长度一致,则说明匹配完一种结果了
        if(x==c.length-1){
    
    
            res.add(String.valueOf(c));
            return;
        }
        Set<Character> set=new HashSet<>();
        //做长度循环
        for(int i=x;i<c.length;i++){
    
    
            //如果哈希集合中存在这个元素,则进入下次循环
            if(set.contains(c[i])) continue;
            //不重复就把这个元素加入哈希集合
            set.add(c[i]);
            //把刚进来的元素跟目标地址的元素进行交换
            swap(i,x);
            //进入下次深度遍历
            dfs(x+1);
            //回溯为交换前的状态
            swap(i,x);
        }
    }
    private void swap(int a,int b){
    
    
        char tmp=c[a];
        c[a]=c[b];
        c[b]=tmp;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41541562/article/details/108375642