zoukankan      html  css  js  c++  java
  • 【剑指offer】38.字符串的排列

    38.字符串的排列

    面试题38. 字符串的排列

    难度中等38

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

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

    示例:

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

    回溯

    //dfs  time :O(N!)  space  : O(N^2)
        List<String> ret = new LinkedList<>();
        char [] ch;
        public String[] permutation(String s) {
            if(s == null){
                return new String[0];
            }
            ch = s.toCharArray();
            dfs(0);
            return ret.toArray(new String[ret.size()]);
        }
    
        private void dfs(int x){
            //终止条件
            if(x == ch.length-1){
                ret.add(String.valueOf(ch));
                return;
            }
            HashSet<Character> hashSet = new HashSet<>();
            
            for(int i=x;i<ch.length;i++){
                //去重 -》剪枝操作
                if(hashSet.contains(ch[i]))  continue;
                hashSet.add(ch[i]);
                //交换
                swap(i,x);
                dfs(x+1);
                //撤回交换
                swap(x,i);
            }
        }
    
        private void swap(int x,int i){
            char tmp = ch[x];
            ch[x] = ch[i];
            ch[i] = tmp;
        }
    
  • 相关阅读:
    解决方案solution
    Marshal类
    鼠标钩子WH_MOUSE_LL和WH_MOUSE的区别
    DllImport
    打包.py文件成.exe
    C++定义全部变量注意项
    类.cpp文件不识别类.h所定义的结构体问题
    C++判断文件是否存在
    博客专栏
    软件测试基础知识
  • 原文地址:https://www.cnblogs.com/qxlxi/p/12860602.html
Copyright © 2011-2022 走看看