基础题测试得了9分多 这题应该算是对了
提供一下自己的思路
- package com.itheima;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.LinkedList;
- import java.util.TreeSet;
- /**
- * 第8题:编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,例如: 原始字符串是"abc",打印得到下列所有组合情况: "a" "b" "c"
- * "ab" "bc" "ca" "ba" "cb" "ac" "abc" "acb" "bac" "bca" "cab" "cba"
- */
- public class Test8 {
- // 计算应该排列的数量(此函数可省)
- // 比如有4个字符时是:A41+A42+A43+A44=4+4*3+4*3*2+4*3*2*1,其中A43=A44
- private static int getCount(int length, int l, int count) {
- int c1 = 1;
- for (int i = length; i >= l; i--) {
- c1 = c1 * i;
- }
- l--;
- if (l == 1) {
- count = count + c1 + c1;
- // System.out.println(length+" "+l+" "+count);
- return count;
- } else {
- count = count + c1;
- // System.out.println(length+" "+l+" "+count);
- return getCount(length, l, count);
- }
- }
- // 排列
- private static void getPermutation(LinkedList<Character> list, String str,
- ArrayList<String> arr) {
- LinkedList<Character> list1 = (LinkedList<Character>) list.clone();
- String str1;
- // 以初始str+list内剩余c进行字符串连接,循环遍历
- for (int j = 0; j < list.size(); j++) {
- char c = list.get(j);
- System.out.print(str + c + " ");
- arr.add(str + c);
- }
- // 在list内循环选c,去除选定的c,递归
- for (int i = 0; i < list1.size(); i++) {
- str1 = str + list1.get(i);
- list1.remove(i);
- getPermutation(list1, str1, arr);
- list1 = (LinkedList<Character>) list.clone();
- }
- }
- public static void main(String[] args) {
- String srcString = "abc";
- int length = srcString.length();
- int count = getCount(length, length, 0);
- System.out.println("应该有:" + count + "种情况");
- LinkedList<Character> list = new LinkedList<Character>();
- ArrayList<String> arr = new ArrayList<String>();
- for (int i = 0; i < length; i++) {
- list.add(srcString.charAt(i));
- }
- System.out.println("生成顺序:");
- getPermutation(list, "", arr);
- System.out.println();
- System.out.println("按需求输出:");
- for (int i = 0, j = 1, count1 = 0; count1 < arr.size(); i++) {
- if (i >= arr.size()) {
- i = 0;
- j++;
- System.out.println();
- } else {
- if ((arr.get(i)).length() == j) {
- System.out.print("\"" + arr.get(i) + "\" ");
- count1++;
- }
- }
- }
- }
- }
复制代码 |