A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 沟门大杏 中级黑马   /  2014-8-2 21:16  /  1217 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

这是一个初级试题,只能打印出"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;
}
}

2 个回复

倒序浏览
入门测试题吧,写两个算法,一个求排列,一个求组合,先求组合,再对组合结果求排列;组合结果如果算法算出的是有重复的,最好用map来存,重复的会被覆盖掉。最后打印结果的时候最好格式化一下,让长度相同的串显示在一行,就和题目要求的一样了,楼主只求了排列,没有求组合,递归的时候把要处理的串传进方法里,只能说这么多了,楼主加油!
回复 使用道具 举报
:'(我也抽到了这道!!迷茫中
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马