次のコードでは、制限された整数パーティション (各番号は各パーティションで 1 回のみ発生する可能性があります) を各パーティションのk
番号でカウントし1
ますm
。このコードは大量のキャッシュ値を生成するため、すぐにメモリ不足になります。
例:
sum := 15, k := 4, m:= 10
期待される結果は6
次の制限付き整数パーティションがあります。
1,2,3,9
、、、、、、1,2,4,8
_ 1,2,5,7
_ 1,3,4,7
_ 1,3,5,7
_2,3,4,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 k1, short k, short start, 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),k,(short)(i+1),end,cache));
}
cache.put(key, tmp);
return tmp;
}
return fetched;
}
キャッシュを回避/削減する公式はありますか? または、制限された整数部分をどのように数えることができますk and m
か?