高分 急求!!!!
将M个A和N个B,组合成一个长度为(M+N)的字符串,每个新组成的字符串中都包含M个A和N个B,现在要输出组合的全部字符串,怎么编程实现?有一定难度哦,望高手解决一下,谢谢。
------解决方案--------------------public class Permutations {
public static void perm(String s) { perm( " ", s); }
private static void perm(String prefix, String s) {
int N = s.length();
if (N == 0) System.out.println(prefix);
else {
for (int i = 0; i < N; i++)
perm(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
}
}
private static void swap(char[] a, int i, int j) {
char c;
c = a[i]; a[i] = a[j]; a[j] = c;
}
private static String builder(char c, int i){
StringBuilder sb = new StringBuilder();
for(int j = 0; j < i; j++)
sb.append(c);
return sb.toString();
}
public static void main(String[] args) {
char A,B;
int M,N;
A = 'a ';
B = 'b ';
M = 2;
N = 3;
String aString = builder(A,M);
String bString = builder(B,N);
perm(aString + bString);
}
}
哈,作业没写完来玩这个。
------解决方案-------------------- int m=5;
int n=4;
String A= "A ";// 0
String B= "B ";// 1
for(int i=0;i <Math.pow(2,m+n);i++){
String str = Integer.toBinaryString(i);
if(str.replaceAll( "0 ", " ").length()==n){
str=str.replaceAll( "0 ", "A ").replaceAll( "1 ", "B ");
for(int j=str.length();j <m+n;j++)
str= "A "+str;
System.out.println(str);
}
}
------解决方案--------------------package test01;
public class Test01 {
private static int get(int m, int n) {// 返回2的m+n次
int add = 1;
for (int i = 1; i <= (m + n); i++)
add = add * 2;
return add;
}
private static int[] covert(int m, int n, int a) {// 把a转为2进制
int AB[] = new int[m + n];
int aa = a;
for (int i = 1; i <= m + n; i++) {
a = aa % 2;
if (aa != 1) {
if (a != 0)
AB[i - 1] = 1;
else
AB[i - 1] = 0;
}
if (aa == 1) {
AB[i - 1] = 1;
break;
}
aa = aa / 2;
}
return AB;
}
public static void main(String[] args) {
int m = 3, n = 2, a;// m表示M个A,n表示N个B;
a = get(m, n);
for (int j = 0; j < a; j++) {
int AB[] = new int[m + n];
int mn = 0;
AB = covert(m, n, j);
for (int i = 0; i < m + n; i++) {
mn = mn + AB[i];
}
if (mn == m) {
StringBuffer s = new StringBuffer();
for (int i = 0; i < m + n; i++) {
if (AB[i] == 1)
s.append( 'A ');
else
s.append( 'B ');
}
System.out.println(s.toString());
}
}
}
}