黑马程序员技术交流社区
标题:
初级试题
[打印本页]
作者:
沟门大杏
时间:
2014-8-2 21:16
标题:
初级试题
这是一个初级试题,只能打印出"abc" "acb" "bac" "bca" "cab" "cba"组合,改哪里能全部出来。代码我也没看明白。
package com.itheima;
import java.util.Arrays;
import java.util.LinkedList;
public class Test8 {
/**
* 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,
例如:原始字符串是"abc",
打印得到下列所有组合情况:
"a" "b" "c"
"ab" "bc" "ca" "ba" "cb" "ac"
"abc" "acb" "bac" "bca" "cab" "cba"
*/
static int 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 )
{
System.out.println (Arrays.toString (cs));
}
}
private static LinkedList<char[]> getSub ()
{
while (count <= len)
{
recursionSub (0, -1);
count++;
}
return list;
}
private static LinkedList<char[]> recursionSub ( int ind, int start )
{
start++;
if (start > count - 1)
{
return null;
}
for ( indexs[start] = 0; indexs[start] < len; indexs[start]++ )
{
recursionSub (0, 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;
}
}
作者:
bbdeyouxang
时间:
2014-8-3 00:12
入门测试题吧,写两个算法,一个求排列,一个求组合,先求组合,再对组合结果求排列;组合结果如果算法算出的是有重复的,最好用map来存,重复的会被覆盖掉。最后打印结果的时候最好格式化一下,让长度相同的串显示在一行,就和题目要求的一样了,楼主只求了排列,没有求组合,递归的时候把要处理的串传进方法里,只能说这么多了,楼主加油!
作者:
李利威
时间:
2014-8-4 22:18
:'(我也抽到了这道!!迷茫中
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2