一、求组合类型的算法:
1、整型数组的所有组合的求法
2 、字符串的所有组合
- 可读性高的解法:
package com.itheima;
import java.awt.List;
import java.util.ArrayList;
/**
* 第七题 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符
例如:
原始字符串是"abc",打印得到下列所有组合情况
"a" "b" "c"
"ab" "bc" "ca" "ba" "cb" "ac"
"abc" "acb" "bac" "bca" "cab" "cba"
思路:1 每行字符个数都是递增 2 下一行的字符是建立在上一行的基础上得到的
即在将第一行字符串长度限定为1,第二行为2....,在第一行数据基础上{a,b,c},创建第二行数据,遍历字符串中所字符,并与第一行数据组合。注意每行字符串长度限制
*/
public class Test12 {
public static void main(String[] args){
print("abcd");
}
//接收一个字符串返回全字符组合情况
public static void print(String str){
//将字符串转化为字符数组
char[] ch = str.toCharArray();
//建立一个存有{"a","b","c"}的集合list1
ArrayList<String> list1 = new ArrayList<String>();
for(int i = 0; i < ch.length; i++){
list1.add(ch[i]+"");
}
for(int i = 0; i < ch.length; i++){
//取得每一行要输出的list集合
list1 = getList(list1, i+1,ch);
//遍历输出集合
for(String s:list1){
System.out.print("\"" + s + "\" ");
}
System.out.println("");
}
}
//取得每一行要输出的list集合
public static ArrayList<String> getList(ArrayList<String> list,int len,char[] ch){
//newList 用来装下一行要遍历的元素,list则代表上一行的元素集合
ArrayList<String> newList = new ArrayList<String>();
//该循环用来取得上一行的元素
for(String s:list){
String str = s;
for(int j = str.length();j < len ;j++){
//遍历字符串中没个元素
for(int i = 0; i < ch.length; i++){
//字符不重复则将Str+ch[i]添加进集合,
if(str.indexOf(ch[i]) == -1){
newList.add(str + ch[i]);
}
}
}
}
return newList.size() == 0 ? list:newList;
}
}
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px; font-weight: bold;">时间复杂度低并且看不懂的解法:</span>
<div><pre name="code" class="java">package com.itheima;
/**
* 第七题 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符
例如:
原始字符串是"abc",打印得到下列所有组合情况
"a" "b" "c"
"ab" "bc" "ca" "ba" "cb" "ac"
"abc" "acb" "bac" "bca" "cab" "cba"
*/
import java.util.*;
public class Test11 {
static int n,count = 0;
static char[] array = { 'a', 'b', 'c' };
static LinkedList <char[]> list = new LinkedList<char[]> ();//转化为集合
static int[] indexs = new int[3];
static int len = array.length;
public static void main(String[] args){
getSub ();
for ( char[] cs : list ) //遍历list
{
//n++;
// if(n%3!=0)
System.out.println(cs);
// else System.out.println(cs);
}
}
private static LinkedList<char[]> getSub () //获取
{
while (count <= len){
recursionSub (-1);
count++;
}
return list;
}
private static LinkedList <char[]> recursionSub ( int start )
{
start++;
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] = array[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;
}
}<span style="white-space:pre"> </span>
欢迎大家批评指正,提出效率更高的算法。