关于全组合的问题,
我在基础测试题中碰到了一个
(主要是测试题提交之后才感觉需要重写,然后重新优化了下代码)
需求:
编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符
例如:
原始字符串是"abc",打印得到下列所有组合情况
"a" "b" "c"
"ab" "bc" "ca" "ba" "cb" "ac"
"abc" "acb" "bac" "bca" "cab" "cba"
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
- import java.util.Scanner;
- public class Test5_pro {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- System.out.println("请输入一个长度大于1的字符串:");
- if (scanner.hasNext()) {
- String str = scanner.next();
- if (str != null && str.length() > 1) {
- printAllStr(str);
- } else {
- System.out.println("请输入一个长度大于1的字符串:");
- }
- }
- }
- private static void printAllStr(String str) {
- ArrayList<String> arrayList = new ArrayList<String>();
- char[] chars = str.toCharArray();
- List<Character> datas = new ArrayList<Character>();
- for(char c : chars){
- datas.add(c);
- }
- for (int i = 1; i <= str.length(); i++) {
- sort(datas, new ArrayList<Character>(), i, arrayList);
- }
- System.out.println("该字符串的全字符组合:");
- int length = 1;
- for (String s : arrayList) {
- if (s.length() > length) {
- System.out.println();
- length++;
- }
- System.out.print(s + "\t");
- }
- }
- private static void sort(List<Character> datas, List<Character> target,
- int num, ArrayList<String> arrayList) {
- if (target.size() == num) {
- char[] tmpCs = new char[num];
- int i = 0;
- for (Character c : target) {
- tmpCs[i++] = c;
- }
- arrayList.add(new String(tmpCs));
- return;
- }
- for (int i = 0; i < datas.size(); i++) {
- List newDatas = new ArrayList(datas);
- List newTarget = new ArrayList(target);
- newTarget.add(newDatas.remove(i));
- sort(newDatas, newTarget, num, arrayList);
- }
- }
- }
复制代码
|