zoukankan      html  css  js  c++  java
  • 面试题 08.07. 无重复字符串的排列组合

    题干

    无重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合,字符串每个字符均不相同。

    示例1:

     输入:S = "qwe"

     输出:["qwe", "qew", "wqe", "weq", "ewq", "eqw"]

    示例2:

     输入:S = "ab"

     输出:["ab", "ba"]

    提示:

    字符都是英文字母。

    字符串长度在[1, 9]之间。

    来源:力扣(LeetCode)

    链接:https://leetcode-cn.com/problems/permutation-i-lcci

    思路

    1.结束条件

    当所有字符都被选取后,即记录该字符结果

    2.选取条件

    遍历,当这个字符没有被选取,则选取,并mark这个字符,进行下一轮回溯法

    代码
    class Solution {
        public String[] permutation(String S) {
            //如果长度为0
            if (S.length() == 0)
                return new String[0];
            //定义答案
            List<String> res = new ArrayList<>();
            //把String类型转化为字符数组
            char[] s = S.toCharArray();
            //定义i一个数组来标识是否已经选取
            boolean[] mark = new boolean[s.length];
            //回溯
            res=dfs(s, mark, "", res);
            String [] ret=new String[res.size()];
            return res.toArray(ret);
        }
        private List<String> dfs(char[] s, boolean[] mark, String tmp, List<String> res) {
            //如果当前选定的数组长度与给定的数组长度相等,说明已经选完了,可以退出了
            if (tmp.length() == s.length) {
                res.add(tmp);
                return res;
            }
            //遍历字符数组找有没有没被选中的
            for (int i=0;i<s.length;i++){
                //如果当前字符没被选中
                if (!mark[i]){
                    //将当前字符表记为选中
                    mark[i]=true;
                    //将该字符加入tmp字符,开始回溯继续找
                    res=dfs(s,mark,tmp+s[i],res);
                    //退回
                    mark[i]=false;
                }
            }
            return res;
        }
    }

    结果

  • 相关阅读:
    设计模式之装饰者模式
    每天一点点
    生财有道
    地图的移动和缩放
    钱分割
    位运算
    ref和out
    使用startCoroutine制定倒计时
    静态类和单例类
    Awake和Start
  • 原文地址:https://www.cnblogs.com/ak918xp/p/14289530.html
Copyright © 2011-2022 走看看