字符串排列
根据输入的字符数组打印出该字符串中字符的所有排列,例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有abc,acb,bac,bca,cab和cba的可能排列。 结果请按字母顺序输出。
public class AllSort {
public void permutation(char[] buf, int start, int end) {
if (start == end) {// 当只要求对数组中一个字母进行全排列时,只要就按该数组输出即可
for (int i = 0; i <= end; i++) {
System.out.print(buf[i]);
}
System.out.println();
} else {// 多个字母全排列
for (int i = start; i <= end; i++) {
char temp = buf[start];// 交换数组第一个元素与后续的元素
buf[start] = buf[i];
buf[i] = temp;
permutation(buf, start + 1, end);// 后续元素递归全排列
temp = buf[start];// 将交换后的数组还原
buf[start] = buf[i];
buf[i] = temp;
}
}
}
public static void main(String[] args) throws Exception {
AllSort allSort = new AllSort();
char[] buf = new char[] { 'a', 'b', 'c' };
allSort.permutation(buf, 0, 2);
}
}
字符串组合
【分析】
求组合的问题,跟求排列的问题类似,很容易的想到递归的实现方式。
在求一个字符串中所有字符的组合的时候,针对一个字符,有两种情况,假设在长度为n的字符串中选择长度为m的组合字符串,
第一是选择长度为n的字符串中的第一个字符,那么要在其余的长度n-1的字符串中选择m-1个字符
第二是不选择长度为n的字符串中的第一个字符,那么要在其余的长度n-1的字符串中选择m个字符
递归结束的条件就是,当m为0,即从字符串中不再选出字符的时候,这个时候已经找到了m个字符的组合,输出即可。还有一个条件是,当输入的字符串是串,自然是不能从中选出任何字符的。
public class TT {
public static void main(String ss[]) {
perm("123");
System.out.println();
}
// 求字符串中所有字符的组合abc>a,b,c,ab,ac,bc,abc
public static void perm(String s) {
List<String> result = new ArrayList<String>();
for (int i = 1; i <= s.length(); i++) {
perm(s, i, result);
}
}
// 从字符串s中选择m个字符
public static void perm(String s, int m, List<String> result) {
// 如果m==0,则递归结束。输出当前结果
if (m == 0) {
for (int i = 0; i < result.size(); i++) {
System.out.print(result.get(i));
}
System.out.println();
return;
}
if (s.length() != 0) {
// 选择当前元素
result.add(s.charAt(0) + "");
perm(s.substring(1, s.length()), m - 1, result);
result.remove(result.size() - 1);//注意:递归出栈时需要移除List中的字符组合
// 不选当前元素
perm(s.substring(1, s.length()), m, result);
}
}
}