编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,例如: 原始字符串是"abc",打印得到下列所有组合情况

时间:2021-04-08 12:29:07

"a" "b""c" 

"ab" "bc""ca" "ba" "cb" "ac"

"abc" "acb""bac" "bca" "cab" "cba"


import java.util.Scanner;

import java.util.TreeSet;

 

publicclass Test6 {

        publicstatic void main(String[] args) {

                Scanner s = new Scanner(System.in);//从键盘输入

               

                String str = s.next();

               // System.out.println(str);

               

                s.close();

                show(str);

               

 

        }

        /**

         *打印各种可能

         *@param str       str是给定的字符串

         */

        privatestatic void show(String str) {

                TreeSet<String> set =saveInSet(newStringBuilder(str),0,new StringBuilder(),new TreeSet<String>());

                for (String s : set) {

                        System.out.println(s);

                }

        }

        /**

         *返回集合,集合包含字符串所有字符的可能组合

         *@param str       给定字符串转换成的StringBuilder对象,主要是为了操作字符方便

         *@param count       计数,对第count进行排列组合

         *@param buff       暂存放某种可能

         *@param set       集合,去除重复元素,例如"aab"以第一个a开头会有aba,以第二个a开头也会有aba

         *@return               返回TreeSet集合

         */

        privatestatic TreeSet<String>saveInSet(StringBuilder str,int count, StringBuilder buff, TreeSet<String> set) {

                for (int i = 0,len = str.length(); i < len; i++) {

                        //获取字符

                        char c = str.charAt(i);

                        //去掉原字符串的某个字符(保证某个字符不被重复利用)

                        str.deleteCharAt(i);

                        //缓存添加该字符

                        buff.append(c);

                        //将该种可能组合存入集合

                       set.add(buff.toString());

                       

                        //str仍包含字符,则递归调用,开始取第二位字符

                        //若还有第三位则继续递归……以此类推

                        if (str.length() !=0) {

                                //count用于记录目前在进行排列组合的第count

                                count++;

                                //递归

                                saveInSet(str,count,buff,set);

                                //n位递归结束后,需要继续对n-1位排列,位数-1

                                count--;

                        }

                       

                        //递归结束后,需要继续对n-1位排列,因此清除第n位的记录

                       buff.deleteCharAt(count);

                        //删除的字符插回str

                        str.insert(i, c);

                }

                //返回集合

                return set;

               

        }

 

}