2
請幫助我找出如何編寫打印所有可能的1到N數字組合的方法。我不能使用數組,集合或字符串。 我需要這樣的輸出(3):數組序列從1到N的排列方法,無數組,java
[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("");
}
}
}
}
http://en.wikipedia.org/wiki/Factorial_number_system可能證明是有用的。 – rici 2015-04-04 19:51:17
提示:在方法內部使用'print',除非適用,否則不使用換行符。 – RealSkeptic 2015-04-04 19:53:28
遞歸可能是你的答案。 – Floris 2015-04-04 20:08:19