2 回答
TA贡献1890条经验 获得超9个赞
n choose k = ( n - 1 choose k - 1) + ( n-1 choose k ) 按照自下而上的动态规划方法的公式 是:
dp[n][k] = dp[n-1][k-1] + dp[n-1][k] if n > k
else if n == k
dp[n][k] = 1
else
dp[n][k] = 0
从n = 1和开始k = 1
dp[1][1] = 1; dp[1][0] = 1;
然后填充一个二维数组直到 dp[n][k]
也可以像您的情况一样通过记忆来完成。您的方法可以更改为:
int[][] dp = new int[group][members];
public static int combinations(int group, int members, int[][] dp ) {
if (members == 1) {
return group;
} else if (members == group) {
return 1;
}
if ( dp[group][members] != 0 ) {
return dp[group][members];
}
int first = 0, second = 0;
if ( members <= group - 1) {
first = combinations( group - 1, members - 1, dp );
second = combinations( group - 1, members );
} else if ( members - 1 <= group - 1 ) {
first = combinations( group - 1, members - 1, dp );
}
dp[group][members] = first + second;
return dp[group][members];
}
TA贡献1820条经验 获得超9个赞
一种方法是进行缓存,这伴随着内存使用的巨大代价。
public static int combinations(int group, int members) {
if (members > group - members) {
members = group - members; // 21 choose 17 is same as 21 choose 4
}
final int[][] cache = new int[group][members];
return combinations(group, members, cache);
}
private static int combinations(int group, int members, int[][] cache) {
if (cache[group - 1][members - 1] > 0) {
return cache[group - 1][members - 1];
}
else if (members == 1) {
cache[group - 1][members - 1] = group;
return group;
}
else if (members == group) {
cache[group - 1][members - 1] = 1;
return 1;
}
else {
return (combinations(group - 1, members - 1, cache) + combinations(group - 1, members, cache));
}
}
我做了一些快速测试(非专业基准),发现原来的方法需要缓存方法的一半时间。看起来所有这些对阵列缓存的读/写都大大减慢了速度。
另一种方法是改变整个公式。
public static int combinations(int group, int members) {
if (members > group - members) {
members = group - members;
}
int answer = 1;
for (int i = group; i > group - members; i--) {
answer *= i;
}
for (int i = 1; i <= members; i++) {
answer /= i;
}
return answer;
}
再次,我用原始方法测试了新方法(我让它们BigInteger用于测试),新方法非常快(原始方法为 26 秒,后者为 0.00 秒,35 选择 15)。
补充一点,我认为使用递归调用的时间复杂度为O((group)(log members)),而使用新公式的时间复杂度为O(members)。
添加回答
举报