求一个字符串的全排列所有情况。
输入:
2
输出:
012
021
102
120
201
210
6
代码实现:
package com.darrenchan; import java.util.*; public class Yongyou { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); String[] array = new String[n + 1]; for (int i = 0; i <= n; i++) { array[i] = i + ""; } List<String> list = new ArrayList<>(); listAll(Arrays.asList(array), "", array.length, list); for (String s : list) { System.out.println(s); } System.out.println(list.size()); } public static void listAll(List candidate, String prefix, int n, List<String> list){ if (prefix.length() == n) { list.add(prefix); } for (int i = 0; i < candidate.size(); i++) { List tmp = new LinkedList(candidate); listAll(tmp, prefix + tmp.remove(i), n, list);//函数中的参数从右边开始解析 } } }