【发布时间】:2014-01-11 04:05:24
【问题描述】:
我有一个方法 perm1 可以打印字符串中所有字符的排列/组合
// print permutation / combination of the characters of the string s (in order)
public static void perm1(String s) { perm1("", s); }
private static void perm1(String prefix, String s) {
int N = s.length();
if (N == 0) System.out.println(prefix);
else {
System.out.println(prefix);
for (int i = 0; i < N; i++)
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
}
}
perm1 工作正常并产生所需的输出。
我正在尝试创建一个类似的方法perm2,它适用于整数数组列表
public static void perm2(ArrayList<Integer> a) {
ArrayList<Integer> sub = new ArrayList<Integer>();
perm2(sub, a);
}
public static void perm2(ArrayList<Integer> sub, ArrayList<Integer> a){
int L = a.size();
if (L==0) System.out.println(sub);
else {
System.out.println(sub);
for (int i = 0; i < L; i++){
sub.add(a.get(i));
a.remove(i);
perm2(sub, a);
L = a.size(); // to avoid Index out of bounds exception
}
}
}
这不会产生我希望的所有排列和组合。使用 arraylist [1, 2, 3],它只打印以下内容:
[]
[1]
[1, 2]
[1, 2, 3]
谁能告诉我如何修改 perm2 以便它打印其他预期值,例如 [2] [3] [2, 3] [3, 2] [2, 3, 1] [2, 1, 3] 等等...
【问题讨论】:
-
什么是完整的期望输出?
-
如果arraylist是{1,2,3},预期输出是{}, {1}, {2}, {3}, {1, 2}, {2, 1} , {1, 3}, {3, 1}, {2, 3}, {3, 2}, {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, { 2, 3, 1}, {3, 1, 2}, {3, 2, 1} - 顺序无关紧要