栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

文章目录
  • 【LeetCode】剑指 Offer 38. 字符串的排列

package offer;

import java.util.HashSet;
import java.util.linkedList;
import java.util.List;

public class Solution38 {
    public static void main(String[] args) {
        String s = "abc";
        Solution38 solution = new Solution38();
        String[] res = solution.method(s);
        System.out.print("[");
        for(int i = 0; i < res.length; i++){
            System.out.print('"');
            System.out.print(res[i]);
            System.out.print('"');
            if(i != res.length - 1) System.out.print(",");
        }
        System.out.print("]");
    }

    char[] c;
    List res = new linkedList<>();

    private String[] method(String s){
        c = s.toCharArray();
        dfs(0);
        return res.toArray(new String[res.size()]);
    }

    private void dfs(int x){
        if(x == c.length - 1){
            res.add(String.valueOf(c));
            return;
        }
        HashSet 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 temp = c[a];
        c[a] = c[b];
        c[b] = temp;
    }
}

//时间复杂度为 O(n*n!)
//空间复杂度为 O(n^2),递归中辅助 Set 累计存储的字符数量最多为 N + (N-1) + ... + 2 + 1 = (N+1)N/2N+(N−1)+...+2+1=(N+1)N/2
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/695196.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号