[英]Editing recursive algorithm: passing array instead of string as an argument to save results instead of printing
我有這個代碼可以從長度為 k 的數組中找到 n 個組合:
class Util
{
// Function to print all distinct combinations of length k
public static void recur(int[] A, String out, int n, int k)
{
// invalid input
if (k > n) {
return;
}
// base case: combination size is k
if (k == 0) {
System.out.println(out);
return;
}
// start from next index till first index
for (int i = n - 1; i >= 0; i--)
{
// add current element A[i] to output and recur for next index
// (i-1) with one less element (k-1)
recur(A, (A[i]) + " " + out, i, k - 1);
}
}
public static void main(String[] args)
{
int[] A = {0, 1, 2, 3 };
int k = 2;
// process elements from right to left
recur(A, "", A.length, k);
}
}
它工作正常,其主要方法打印
2 3
1 3
0 3
1 2
0 2
0 1
但是我想將這些組合保存在一個列表中: List<int[]>
或List<List<Integer>>
。 我試圖編輯算法:
public static void recur(int[] A, List<Integer> out, int n, int k)
{
// invalid input
if (k > n) {
return;
}
// base case: combination size is k
if (k == 0) {
System.out.println(out);
return;
}
// start from next index till first index
for (int i = n - 1; i >= 0; i--)
{
out.add(A[i]);
// add current element A[i] to output and recur for next index
// (i-1) with one less element (k-1)
recur(A, out, i, k - 1);
}
}
但它沒有按預期工作:它打印
[3, 2]
[3, 2, 1]
[3, 2, 1, 0]
[3, 2, 1, 0, 2, 1]
[3, 2, 1, 0, 2, 1, 0]
[3, 2, 1, 0, 2, 1, 0, 1, 0]
對於這個主要方法:
public static void main(String[] args)
{
int[] A = {0, 1, 2, 3 };
int k = 2;
recur(A, new ArrayList<>(), A.length, k);
}
String 輸出的第一種情況有效,因為 String 是不可變的,因此您可以傳遞它而不會損害原始內容。
ArrayList的第二種情況將不起作用,因為您傳遞了一個引用,並且當您修改“引用”的內容時,您會修改原始內容。
在典型的回溯中,您缺少選擇 - 探索 - 取消選擇方法的取消選擇部分。
你的選擇部分是out.add(A[i])
你的探索部分是recur(A, out, i, k - 1)
您的Unchoose部分應該是刪除您上次選擇的元素,即列表的最后一個元素: out.remove(out.size()-1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.