【发布时间】:2015-04-04 19:45:25
【问题描述】:
请帮助我了解如何编写打印从 1 到 N 的所有可能的数字组合的方法。我不能使用数组、集合或字符串。 我需要这样的输出(对于 3):
[1] [2] [3]
[1] [3] [2]
[2] [1] [3]
[2] [3] [1]
[3] [2] [1]
[3] [1] [2]
用数组写这样的方法是没有问题的:
public class Test {
static void permute(int[] a, int k) {
if (k == a.length) {
for (int i = 0; i < a.length; i++) {
System.out.print(" [" + a[i] + "] ");
}
System.out.println();
} else {
for (int i = k; i < a.length; i++) {
int temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
public static void main(String args[]) {
int N = 3;
int[] sequence = new int[N];
for (int i = 0; i < N; i++) {
sequence[i] = i + 1;
}
permute(sequence, 0);
}
}
提前感谢您的帮助!
UPD 1. 我也在尝试写这样的东西(但不成功):
public class Combinations {
private static int change;
public void doIt(int n, int pos) {
if (pos == n) {
for (int f = 1; f <= n; f++) {
System.out.print(f + " ");
}
System.out.println("");
} else {
for (int i = pos; i < n; i++) {
change = pos;
System.out.print(change + " ");
pos = i;
System.out.print(pos + " ");
i = change;
System.out.print(i + " ");
System.out.println("");
doIt(n, pos + 1);
change = pos;
System.out.print(change + " ");
pos = i;
System.out.print(pos + " ");
i = change;
System.out.print(i + " ");
System.out.println("");
}
}
}
}
【问题讨论】:
-
提示:在你的方法中使用
print,除非在适当的地方没有换行符。 -
递归可能是你的答案。
-
@Floris 我同意你的观点,但我需要一些提示。在 UPD 中,我写了我对这种方法的尝试。我不知道如何使它工作。
-
@VasylHoshovsky 冒着听起来重复的风险——只要 collections 是指 Java 的 collections framework 中的类,那么它原则上可能是微不足道的(尽管在实践中有点麻烦)用BitSets 来重现你的数组使用解决方案。但除此之外,我不太确定这个问题是否有解决方案,尽管我的直觉是它应该是可行的。 =(
标签: java algorithm recursion permutation