我在向量容器中有10个数字包含:1,2,3,4,5,6,7,8,9,10。我想在一个组中有n个数字,例如:
n = 3
[1,2,3],[4,5,6],[7,8,9],[10] [2,3,4],[5,6,7],[8,9,10],[1]
是否有算法可以找到所有组合?
int[] input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int k = 3;
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++);
subsets.add(getSubset(input, s));
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;
}
subsets.add(getSubset(input, s));
}
}
System.out.println();
for(int i = 0; i < subsets.size();i++) {
int[] result = subsets.get(i);
for(int j = 0; j < result.length; j++) {
System.out.print(result[j]+" ");
}
System.out.println();
}
}
int[] getSubset(int[] input, int[] subset) {
int[] result = new int[subset.length];
for (int i = 0; i < subset.length; i++)
result[i] = input[subset[i]];
return result;
}
谢谢。