使用嵌套循环获取字符串的排列
Getting permutation of a string using nested loops
我已经编写了一个递归方法,使用嵌套循环来打印给定的所有排列 string.It 打印所有排列,但是有人可以不止一次地找出问题以及改变条件来解决这个问题吗?
public static String swap(String x,int a,int b){
char list[]=x.toCharArray();
char tmp=x.charAt(a);
list[a]=list[b];
list[b]=tmp;
return new String(list);
}
public static void perm(String x,String base){
if(base.length()==3)
System.out.println(base);
for(int i=0;i<x.length();i++)
for(int j=i;j<x.length();j++){
String tmp=swap(x,i,j);
perm(tmp.substring(1),base+tmp.charAt(0));
}
}
示例:
输入:"abc"。
输出:
美国广播公司
交流电
美国广播公司
背
bca
背
CBA
出租车
CBA
美国广播公司
交流电
美国广播公司
交流电
美国广播公司
交流电
美国广播公司
交流电
abc.
下面是我根据你的代码做的修改版本。
public static void main(String[] args) {
String str = "abc";
char[] chars = str.toCharArray();
perm(chars, 0);
}
public static void swap(char[] x, int a, int b) {
char tmp = x[a];
x[a] = x[b];
x[b] = tmp;
}
public static void perm(char[] x, int idx) {
if (idx == x.length) {
for (int i = 0; i < x.length; i++)
System.out.print(x[i]);
System.out.println();
}
for (int i = idx; i < x.length; i++) {
swap(x, idx, i);
perm(x, idx + 1);
swap(x, idx, i);
}
}
我已经编写了一个递归方法,使用嵌套循环来打印给定的所有排列 string.It 打印所有排列,但是有人可以不止一次地找出问题以及改变条件来解决这个问题吗?
public static String swap(String x,int a,int b){
char list[]=x.toCharArray();
char tmp=x.charAt(a);
list[a]=list[b];
list[b]=tmp;
return new String(list);
}
public static void perm(String x,String base){
if(base.length()==3)
System.out.println(base);
for(int i=0;i<x.length();i++)
for(int j=i;j<x.length();j++){
String tmp=swap(x,i,j);
perm(tmp.substring(1),base+tmp.charAt(0));
}
}
示例: 输入:"abc"。 输出: 美国广播公司 交流电 美国广播公司 背 bca 背 CBA 出租车 CBA 美国广播公司 交流电 美国广播公司 交流电 美国广播公司 交流电 美国广播公司 交流电 abc.
下面是我根据你的代码做的修改版本。
public static void main(String[] args) {
String str = "abc";
char[] chars = str.toCharArray();
perm(chars, 0);
}
public static void swap(char[] x, int a, int b) {
char tmp = x[a];
x[a] = x[b];
x[b] = tmp;
}
public static void perm(char[] x, int idx) {
if (idx == x.length) {
for (int i = 0; i < x.length; i++)
System.out.print(x[i]);
System.out.println();
}
for (int i = idx; i < x.length; i++) {
swap(x, idx, i);
perm(x, idx + 1);
swap(x, idx, i);
}
}