zoukankan      html  css  js  c++  java
  • 分解让复杂问题简单化:字符串的排列

      输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。 

    import java.util.ArrayList;
    import java.util.Collections;
    public class Solution {
        public ArrayList<String> Permutation(String str) {
            ArrayList<String> res = new ArrayList<String>();
            if (str != null && str.length() > 0) {
                PermutationHelper(str.toCharArray(), 0, res);
                Collections.sort(res);
            }
            return res;
        }
    
        private static void PermutationHelper(char[] cs, int position,
                ArrayList<String> list) {
            if (position == cs.length - 1) { // 解空间的一个叶节点
                list.add(String.valueOf(cs)); // 找到一个解
            } else {
                for (int j = position; j < cs.length; ++j) {
                    if (j == position || cs[j] != cs[position]) {
                        swap(cs, position, j);
                        PermutationHelper(cs, position + 1, list);
                        swap(cs, position, j); // 复位
                    }
                }
            }
        }
    
        private static void swap(char[] cs, int i, int j) {
            char temp = cs[i];
            cs[i] = cs[j];
            cs[j] = temp;
        }
    }
  • 相关阅读:
    DDD框架基础知识
    ORM之Entity Framework(EF)
    ORM之Dapper
    ORM基础知识
    DI 依赖注入之unity的MVC版本使用Microsoft.Practices.Unity1.2与2.0版本对比
    ssh免密连接远程服务器
    Java字节码
    VIM基本命令及自用配置
    Linux字符设备驱动实现
    Python绘图matplotlib
  • 原文地址:https://www.cnblogs.com/SaraMoring/p/5822275.html
Copyright © 2011-2022 走看看