本帖最后由 李金中 于 2014-2-10 01:46 编辑
编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符
例如
原始字符串是"abc",打印得到下列所有组合情况
"a" "b" "c"
"ab" "bc" "ca" "ba" "cb" "ac"
"abc" "acb" "bac" "bca" "cab" "cba"
本人想法:递归肯定的。当n = 1时, 找出所有单个字母组成的字符串,存为cArr[n];当n = m 时,可以将cArr[n]遍历插入当n = m - 1 时的字符串数组的每一个元素后,即得。比如 n = 2时, 可以将 a, b, c分别插入n = 1时的字符串数组元素(且该元素不包括带插入的元素)"a", "b", "c"后,得 "ba" "ca" "ab" "cb" "ac""bc"
同理可得 n = 3时的字符串数组。 程序如下:
public class Test6 {
public static void main(String[] args)
{
ArrayList<StringBuilder> strDes = new ArrayList<StringBuilder>();
String strSource = "abc";
int length = 3;
new Test6().printAll(strSource, strDes, length);
}
public void printAll(String strSource, ArrayList<StringBuilder> strDes, int length)
{
char[] cArr = strSource.toCharArray();
int lengthSource = strSource.length();
ArrayList<StringBuilder> strTemp = new ArrayList<StringBuilder>();
if(length == 1)
{
for(int indexDes = 0; indexDes < lengthSource; indexDes++)
{
strDes.add(new StringBuilder().append( cArr[indexDes] + ""));
}
}
else
{
length--;
printAll(strSource, strDes, length);
for(int index = 0; index < lengthSource; index++)
{
for(int indexDes = 0; indexDes < strDes.size(); indexDes++)
{
if((strDes.get(indexDes).indexOf(cArr[index] + "")) == -1)
{
StringBuilder strBuilderTemp = new StringBuilder(strDes.get(indexDes));
strBuilderTemp.append(cArr[index] + "");
strTemp.add(strBuilderTemp);
}
}
}
strDes = strTemp;
}
for(int indexDes = 0; indexDes < strDes.size(); indexDes++)
{
System.out.print("\"" + strDes.get(indexDes).toString() + "\"");
}
System.out.println();
}
}
为什么打印结果是:
"a""b""c"
"ba""ca""ab""cb""ac""bc"
"ba""ca""ab""cb""ac""bc"
哪里出错,怎么修改? |
|