zoukankan      html  css  js  c++  java
  • [CC150] Get all permutations of a string

    Problem: Compute all permutations of a string of unique characters.

    此题用循环的方式不好做,下面是一种递归的思路:

    把给的字符串看成一个字符集合,每次从这个集合里拿出一个字符来填到下面的空格中。填的顺序从左到右。

    把a1填到第一个空格里是一种情况,集合剩下的部分填到2-9的空格里;

    把a2填到第一个空格里是一种情况,集合剩下的部分填到2-9的空格里;

    。。。。。。

    这样递归的进行下去,直到集合里没有剩余,所有的情况就被穷尽了。

        public ArrayList<String> getPerms(String str){
            ArrayList<String> result = new ArrayList<String>();
            getPerms("", str, result);
            return result;
        }
        
        public void getPerms(String prefix, String str, ArrayList<String> result){
            if(str == null || str.length() == 0){
                result.add(prefix);
                return;
            }
            
            for(int i = 0; i < str.length(); ++i){
                char ch = str.charAt(i);
                getPerms(prefix+ch, str.substring(0, i) + str.substring(i+1), result);
            }
        }
  • 相关阅读:
    docker-5-容器数据卷
    docker-4-镜像
    docker-3-常用命令(下)
    docker-3-常用命令(中)
    docker-3-常用命令(上)
    docker-2-安装
    Python中Unicode字符串
    Python中整数和浮点数
    Python中什么是变量
    Python中数据类型
  • 原文地址:https://www.cnblogs.com/Antech/p/3771875.html
Copyright © 2011-2022 走看看