java 输入一个字符串,打印出该字符串中字符的所有排列

package com.importent;

import java.util.ArrayList;
import java.util.List;

//java传入一个数组{1,2,3},返回123,132,213,231,312,321(全排列)
public class TestString6 {
public static void main(String[] args) {
String[] array = { "1", "2", "3", "4" };
List<String> list = new ArrayList();
execute(array, list);
}

public static void execute(String[] array, List<String> list) {
for (int i = 0; i < array.length; i++) {
if (list.contains(array[i])) {
continue;
}
list.add(array[i]);
if (list.size() == array.length) {
String str = "";
for (int n = 0; n < list.size(); n++) {
str += list.get(n);
}
System.out.println(str);
} else {
execute(array, list);
}

list.remove(list.size() - 1);

}
}
}
不理解为什么list.remove(list.size()-1)执行结果只能到
1234
1243
list.size每次执行的时候都是3,3-1=2每次都删除索引位置是2的值,怎么出现的
1324
1342
1423
1432
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
3412
3421
4123
4132
4213
4231
4312
4321

实现思路:就是输入字符串后,通过递归的方式,循环每个位置和其他位置的字符。

import java.util.Scanner;
 
public class Demo001 {
     
    public static void main(String[] args) {
        String str = "";
         
        Scanner scan = new Scanner(System.in);
         
        str = scan.nextLine();
         
        permutation(str.toCharArray(), 0);
    }
 
    public static void permutation(char[] str, int i) {
        if (i >= str.length)
            return;
        if (i == str.length - 1) {
            System.out.println(String.valueOf(str));
        } else {
            for (int j = i; j < str.length; j++) {
                char temp = str[j];
                str[j] = str[i];
                str[i] = temp;
 
                permutation(str, i + 1);
 
                temp = str[j];
                str[j] = str[i];
                str[i] = temp;
            }
        }
    } 
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-06-22
import java.util.Scanner;public class Demo001 { public static void main(String[] args) { String str = ""; Scanner scan = new Scanner(System.in); str = scan.nextLine(); permutation(str.toCharArray(), 0); } public static void permutation(char[] str, int i) { if (i >= str.length) return; if (i == str.length - 1) { System.out.println(String.valueOf(str)); } else { for (int j = i; j < str.length; j++) { char temp = str[j]; str[j] = str[i]; str[i] = temp; permutation(str, i + 1); temp = str[j]; str[j] = str[i]; str[i] = temp; } } }}运行结果:追问

看我的要求

本回答被提问者采纳
相似回答