zoukankan      html  css  js  c++  java
  • 牛客(27)字符串的排列

    //    题目描述
    //    输入一个字符串,按字典序打印出该字符串中字符的所有排列。
    //    例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
    
        //    输入描述:
    //    输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
        public static ArrayList<String> Permutation(String str) {
            ArrayList<String> arrayList = new ArrayList<String>();
            char[] chars = str.toCharArray();
            Permutation(chars, 0, arrayList);
    //      按字典序打印
            TreeSet<String> strings = new TreeSet<String>(arrayList);
            arrayList.clear();
            arrayList.addAll(strings);
            return arrayList;
        }
    
        public static void Permutation(char[] chars, int start, ArrayList<String> arrayList) {
            //结束条件
            if (start > chars.length - 1 || chars == null) {
                return;
            }
    
            if (start == chars.length - 1) {
                arrayList.add(String.valueOf(chars));
            } else {
    
                for (int i = start ; i < chars.length; i++) {
                    if (i==start){
                        //start 是第一个
                        Permutation(chars, start + 1, arrayList);
                    }else{
                        //start 不是第一个
                        //交换
                        swap(chars, start, i);
    
                        Permutation(chars, start + 1, arrayList);
    
                        //恢复
                        swap(chars, start, i);
                    }
                }
            }
        }
    
        public static void swap(char[] chars, int start, int end) {
            char temp = chars[start];
            chars[start] = chars[end];
            chars[end] = temp;
        }
  • 相关阅读:
    poj 1904 King's Quest
    【BZOJ】1051: [HAOI2006]受欢迎的牛
    hdu 2767 Proving Equivalences
    hdu 3234 Exclusive-OR
    poj 1988 Cube Stacking
    poj 1733 Parity game
    hdu 3047 Zjnu Stadium 带权并查集
    poj 1182 食物链 种类并查集
    HDU 3749 Financial Crisis
    【BZOJ】1046 : [HAOI2007]上升序列
  • 原文地址:https://www.cnblogs.com/kaibing/p/9024883.html
Copyright © 2011-2022 走看看