Làm thế nào về một giải pháp mà sẽ không quan tâm nếu bạn thay đổi kích thước của ArrayList?
public static void main(String args[]) {
ArrayList<Integer> ali = new ArrayList<>();
ali.add(1);
ali.add(2);
ali.add(3);
System.out.println(combinations(ali).toString().replace("], [", "],\n ["));
}
Đây chỉ là một chút trợ giúp khi bắt đầu.
public static List<List<Integer>> combinations(List<Integer> input) {
return step(input, input.size(), new ArrayList<>());
}
Đây là phương pháp đệ quy,
public static List<List<Integer>> step(List<Integer> input,
int k,
List<List<Integer>> result) {
// We're done
if (k == 0) {
return result;
}
// Start with [[1], [2], [3]] in result
if (result.size() == 0) {
for (Integer i : input) {
ArrayList<Integer> subList = new ArrayList<>();
subList.add(i);
result.add(subList);
}
// Around we go again.
return step(input, k - 1, result);
}
// Cross result with input. Taking us to 2 entries per sub list. Then 3. Then...
List<List<Integer>> newResult = new ArrayList<>();
for (List<Integer> subList : result) {
for(Integer i : input) {
List<Integer> newSubList = new ArrayList<>();
newSubList.addAll(subList);
newSubList.add(i);
newResult.add(newSubList);
}
}
// Around we go again.
return step(input, k - 1, newResult);
}
Đầu ra:
[[1, 1, 1],
[1, 1, 2],
[1, 1, 3],
[1, 2, 1],
[1, 2, 2],
[1, 2, 3],
[1, 3, 1],
[1, 3, 2],
[1, 3, 3],
[2, 1, 1],
[2, 1, 2],
[2, 1, 3],
[2, 2, 1],
[2, 2, 2],
[2, 2, 3],
[2, 3, 1],
[2, 3, 2],
[2, 3, 3],
[3, 1, 1],
[3, 1, 2],
[3, 1, 3],
[3, 2, 1],
[3, 2, 2],
[3, 2, 3],
[3, 3, 1],
[3, 3, 2],
[3, 3, 3]]
Ý bạn là tổng kết hợp chiều dài 3. Có lẽ một phần của đệ quy sẽ liên quan đến việc tìm kiếm tổng số kết hợp chiều dài 2. Sau đó bạn sẽ cần phải thêm một ký tự bổ sung cho mỗi kết hợp ngắn hơn đó. Vì vậy, tôi nghĩ chiều dài sẽ là chỉ số đệ quy. Hãy suy nghĩ về bước cơ bản của đệ quy có thể là gì. –