问题描述
使用以下代码,我计算受限整数分区(每个数字只能在每个分区中出现一次),每个分区中有k
个数字,每个数字等于或大于1
,但不等于大于m
。这段代码会生成大量缓存值,因此会很快耗尽内存。
示例:
sum := 15,k := 4,m:= 10
的预期结果是6
具有以下受限制的整数分区:
1,2,3,9
,1,4,8
,1,5,7
,1,7
,2,6
public class Key{
private final int sum;
private final short k1;
private final short start;
private final short end;
public Key(int sum,short k1,short start,short end){
this.sum = sum;
this.k1 = k1;
this.start = start;
this.end = end;
}
// + hashcode and equals
}
public BigInteger calcRestrictedIntegerPartitions(int sum,short k,short m){
return calcRestrictedIntegerPartitionsHelper(sum,(short)0,k,(short)1,m,new HashMap<>());
}
private BigInteger calcRestrictedIntegerPartitionsHelper(int sum,short end,Map<Key,BigInteger> cache){
if(sum < 0){
return BigInteger.ZERO;
}
if(k1 == k){
if(sum ==0){
return BigInteger.ONE;
}
return BigInteger.ZERO;
}
if(end*(k-k1) < sum){
return BigInteger.ZERO;
}
final Key key = new Key(sum,(short)(k-k1),start,end);
BigInteger fetched = cache.get(key);
if(fetched == null){
BigInteger tmp = BigInteger.ZERO;
for(short i=start; i <= end;i++){
tmp = tmp.add(calcRestrictedIntegerPartitionsHelper(sum-i,(short)(k1+1),(short)(i+1),end,cache));
}
cache.put(key,tmp);
return tmp;
}
return fetched;
}
是否有避免/减少缓存的公式?或如何用k and m
计算受限整数部分?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)