编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,
例如:原始字符串是"abc",
打印得到下列所有组合情况:
"a" "b" "c"
"ab" "bc" "ca" "ba" "cb" "ac"
改编
例如:原始字符串是"abc",
打印得到下列所有组合情况:
"a" "b" "c"
"ab" "bc" "ca" "ba" "cb" "ac"
"abc" "acb" "bac" "bca" "cab" "cba"
此题采用排列组合的算法
摘自网路
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Plzh {
private static char[] is ;
private static int total;
private static int m;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> iL = new ArrayList<Integer>();
System.out.println("请输入一串字符");
String next = sc.next();
is = next.toCharArray();
m=next.length();
for (int i = 1; i <= m; i++) {
new Plzh().plzh("", iL, i);
System.out.println();
}
System.out.println("total : " + total);
}
private void plzh(String s, List<Integer> iL, int m) {
if(m == 0) {
System.out.print(s+"\t");
total++;
return;
}
List<Integer> iL2;
for(int i = 0; i < is.length; i++) {
iL2 = new ArrayList<Integer>();
iL2.addAll(iL);
if(!iL.contains(i)) {
String str = s + is[i];
iL2.add(i);
plzh(str, iL2, m-1);
}
}
}
}
改编
import java.util.Scanner;
public class Group {
private static char[] is ;
private static int total;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
System.out.println("请输入一串字符");
String next = sc.next();
is = next.toCharArray();
int m=next.length();
for (int i = 1; i <= m; i++) {
group("", sb, i);
System.out.println();
}
System.out.println("total : " + total);
}
public static void group(String s, StringBuilder sb, int m) {
if(m == 0) {
System.out.print(s+"\t");
total++;
return;
}
StringBuilder sb2;
for(int i = 0; i < is.length; i++) {
sb2 = new StringBuilder();
sb2.append(sb);
if(sb.indexOf(String.valueOf(i))==-1) {
String str = s + is[i];
sb2.append(i);
group(str, sb2, m-1);
}
}
}
}