第1个回答 2010-06-03
public class Loop {
public static void main(String[] args) {
// 求组成如下字符串的所有字符可能的组合
String str = "123456";
// 组合后字符串长度,当为元素无重复模式时,这个值要不大于元素个数
int len = 6;
// loop(new char[]{},str.toCharArray(),len);
loop(new char[] {}, str.toCharArray(), len);
}
// 元素无重复
public static void loopNoDup(char[] t, char[] a, int l) {
if (l > 1) {
for (int i = 0; i < a.length; i++) {
char[] b = new char[a.length - i - 1];
System.arraycopy(a, i + 1, b, 0, b.length);
char[] c = new char[t.length + 1];
System.arraycopy(t, 0, c, 0, t.length);
c[t.length] = a[i];
loopNoDup(c, b, l - 1);
}
} else {
for (int i = 0; i < a.length; i++) {
process(t, a[i]);
}
}
}
// 元素可重复
public static void loop(char[] t, char[] a, int l) {
if (l > 1) {
for (int i = 0; i < a.length; i++) {
char[] b = new char[t.length + 1];
System.arraycopy(t, 0, b, 0, t.length);
b[t.length] = a[i];
loop(b, a, l - 1);
}
} else {
for (int i = 0; i < a.length; i++) {
process(t, a[i]);
}
}
}
private static void process(char[] t, char c) {
for (char i : t)
System.out.print(i);
System.out.println(c);
}
public static final void nestedForLoop(int[][] d,int x,int y){
if(y==d[x].length)
return;
ring(d,x);
if(x>0){
nestedForLoop(d,x-1,0);
nestedForLoop(d,x,y+1);
}
else{
print(d);
nestedForLoop(d,x,y+1);
}
}
private static final void ring(int[][] d,int x) {
int t=d[x][d[x].length-1];
for(int i=d[x].length-1; i>0; i--)
d[x][i]=d[x][i-1];
d[x][0]=t;
}
private static final void print(int[][] d) {
for(int i=0; i<d.length; i++)
System.out.print(d[i][0]);
System.out.println();
}
}
第2个回答 2010-06-03
这个比较简单,可以用户输入,只是不能判断重复。
import java.io.*;
class test{
String s;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
test(){
try{s=br.readLine();
}catch(IOException e){System.err.println("输入错误!");}
char[] c=new char[s.length()];
c=s.toCharArray();
System.out.println("排列如下:");
setChar(c,0,s.length()-1);
}
void setChar(char[] cc,int a,int b){
String ss=String.valueOf(cc);
if(a==b)show(cc);
for (int i=a; i<b+1;i++){
char t=cc[a];cc[a]=cc[i];cc[i]=t;
setChar(cc,a+1,b);
cc=ss.toCharArray();
}
}
void show(char[] chars){
System.out.println(String.valueOf(chars));
}
}
public class AllSet{
public static void main (String[] args) {
new test();
}
}