java-使用递归将其元素加起来为n的子集的列表

提问

``````public static void printSublists(ArrayList numbers, ArrayList sublist, int n,
int i) {

if (sublist.sum() == n) {
System.out.println(sublist.toString());
}
else {
for (int j = 0; j < numbers.size(); j++) {
printSublists(numbers, sublist, n, i + 1);
sublist.remove(numbers.get(i));
}
}
}
``````

``````numbers = [1, 3, 4]
n = 4
i = 0
sublist = []
``````

最佳答案

``````                        [1234]
[123]  [234]
[12] [23]   [34]
[1][2]  [3]    [4]
``````

``````public static void main (String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
printSublists(list, list, 4, true, 0);
}

public static void printSublists(List<Integer> numbers, List<Integer> sublist, int n, boolean walkRight, int level) {

// the test
if (sum(sublist) == n)
System.out.println(sublist);

// the exit criteia (leaf reached)
if (sublist.size() == 1)
return;

// visit the right sublist
if (walkRight)
printSublists(numbers, sublist.subList(0, sublist.size()-1), n, walkRight, level+1);

// we only walk the right path once
walkRight = false;

// visit the left sublist
printSublists(numbers, sublist.subList(1, sublist.size()), n, walkRight, level+1);
}
``````

``````[1, 3]
[4]
[4, 0]
``````