我有遞歸合併功能:Java的遞歸組合函數迭代相當於
static void combinations2(String[] arr, int len, int startPosition, String[] result) {
if (len == 0) {
for (String n : result) {
System.out.print(n + " \n");
}
return;
}
for (int i = startPosition; i <= arr.length - len; i++) {
result[result.length - len] = arr[i];
combinations2(arr, len - 1, i + 1, result);
}
}
輸入:
arr = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"} - input array e.g.
len = 3 - length of each combination
startPosition = 0
result - result of each combination
輸出:
Item 1
Item 2
Item 3
Item 1
Item 2
Item 4
Item 1
Item 2
Item 5
Item 1
Item 3
Item 4
Item 1
Item 3
Item 5
Item 1
Item 4
Item 5
Item 2
Item 3
Item 4
Item 2
Item 3
Item 5
Item 2
Item 4
Item 5
Item 3
Item 4
Item 5
我應該怎麼做將其更改爲迭代替代?我閱讀了關於堆棧的內容,並且我寫了幾行代碼......但是返回函數呢?如何處理它?
我做了財產以後這樣的:
static void combinations2(String[] arr, int len, int startPosition, String[] result) {
Stack<Integer> stos = new Stack<>();
stos.push(startPosition);
stos.push(len);
int i = 0;
while (!stos.isEmpty()) {
len = stos.pop();
startPosition = stos.pop();
if (len == 0) {
for (String n : result) {
System.out.print(n + " \n");
}
System.out.println(" ");
stos.push(startPosition);
stos.push(len+1);
} else {
for (i = startPosition; i <= arr.length - len; i++) {
result[result.length - len] = arr[i];
//combinations2(arr, len - 1, i + 1, result);
stos.push(i + 1);
stos.push(len - 1);
break;
}
}
}
}
,我已經得到了輸出:
Item 1
Item 2
Item 3
Item 1
Item 2
Item 4
Item 1
Item 2
Item 5
有人能告訴我的方式,生成接下來的步驟?
是不是第一個輸出是你想要的輸出?你想通過第二個程序獲得什麼類型的輸出? – niiraj874u
完全一樣,但使用迭代方法... – piotrowicki