【发布时间】:2014-07-17 10:07:09
【问题描述】:
给定一个整数集,{x | 1
例如,这可以解决问题:
public static void combo(int[] combo, int index, int f, int t) {
if (index >= combo.length) {
// display combination
// ...
return;
}
for (int i = f; i <= t - (combo.length - index) + 1; i++) {
combo[index] = i;
combo(combo, index + 1, i + 1, t);
}
}
对于上述情况,调用 combo(new int[]{0, 0, 0, 0}, 0, 1, 9) 将按排序顺序列出所有 9C4 组合,共 126 个。
我想要的是以下内容。给定 k,我希望算法给出组合。
// Select r from c and return combination k.
public static int[] combo(int c, int r, int k) {
}
例如,combo(3,2,1) 应该返回 {1,2},combo(3,2,3) 应该返回 {2,3}(假设第一个组合是 1 而不是 0 - 但这是琐碎的)。
在 O(nCr) 中执行此操作很容易并且占用很少的内存...在 O(1) 中执行此操作也很容易,但是对于较大的组合需要大量内存并且需要预先计算。我不知道是否有可能在不使用查找表的情况下比 O(nCr) 在更好的时间内做到这一点。任何确认/指导将不胜感激。
【问题讨论】:
标签: java algorithm combinations