编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,例如:
原始字符串是"abc",打印得到下列所有组合情况:
"a" "b" "c"
"ab" "bc" "ca" "ba" "cb" "ac"
"abc" "acb" "bac" "bca" "cab" "cba"
import java.util.LinkedList;
public class Test6{
static int n,count = 0;
static char[] arr = {'a','b','c'};
//把字符数组转成串集合
static LinkedList<char[]> list = new LinkedList<char[]>();
static int[] indexs = new int[3];
static int len = arr.length;
public static void main(String[] args) {
getSub();
//使用增强for进行遍历list
for(char[] cs :list)
System.out.println(cs);
}
//获取Sub
private static LinkedList<char[]> getSub(){
while (count<=len){
recursionSub(-1);
count++;
}
return list;
}
private static LinkedList<char[]> recursionSub(int start){
start++;
//把start和count-1进行比较 判断大小
if(start>count-1) {
return null;
}
for(indexs[start] = 0; indexs[start] < len; indexs[start]++){
recursionSub(start);
if(start ==count-1){
char[] temp = new char[count];
for ( int i = count - 1; i >= 0; i-- ){
temp[start - i] = arr[indexs[start - i]];
}
boolean flag = true;
for ( int i = 0; i < temp.length; i++ ){
for ( int j = i+1; j < temp.length; j++ ){
if (temp[i] == temp[j]){
flag = false;
break;
}
}
}
if (flag){
list.add (temp);
}
}
}
return list;
}
} |
|