﻿ 从数组(Java)获取大小为n的所有组合的算法？ - 代码日志

#### 从数组(Java)获取大小为n的所有组合的算法？

``````import java.util.List;
import java.util.ArrayList;

public class combinatorics{
public static void main(String[] args) {

List<int[]> list = new ArrayList<int[]>();
int[] arr = {1,2,3,4,5};
combinations3(arr,list);
listToString(list);
}

static void combinations3(int[] arr, List<int[]> list){
for(int i = 0; i<arr.length-2; i++)
for(int j = i+1; j<arr.length-1; j++)
for(int k = j+1; k<arr.length; k++)
}

private static void listToString(List<int[]> list){
for(int i = 0; i<list.size(); i++){ //iterate through list
for(int j : list.get(i)){ //iterate through array
System.out.printf("%d ",j);
}
System.out.print("\n");
}
}
}
``````

``````[0, 5, 6] <-- scan from the end: "6" cannot be incremented, "5" also, but "0" can be
[1, ?, ?] <-- "0" -> "1"
[1, 2, 3] <-- fill up remaining elements

next iteration:

[1, 2, 3] <-- "3" can be incremented
[1, 2, 4] <-- "3" -> "4"
``````

``````int[] input = {10, 20, 30, 40, 50};    // input array
int k = 3;                             // sequence length

List<int[]> subsets = new ArrayList<>();

int[] s = new int[k];                  // here we'll keep indices
// pointing to elements in input array

if (k <= input.length) {
// first index sequence: 0, 1, 2, ...
for (int i = 0; (s[i] = i) < k - 1; i++);
for(;;) {
int i;
// find position of item that can be incremented
for (i = k - 1; i >= 0 && s[i] == input.length - k + i; i--);
if (i < 0) {
break;
}
s[i]++;                    // increment this item
for (++i; i < k; i++) {    // fill up remaining items
s[i] = s[i - 1] + 1;
}