我实现了递归算法来计算 N 选择 r。C(n,r) = C(n-1,r-1) + C(n-1,r)。我想计算 C(100000, 50000),它抛出了 stackoverflow。感谢任何帮助。
错误:
java 解决方案 1 1 1 10000 5000 线程“main”中的异常 java.lang.StackOverflowError at java.lang.System.arraycopy(Native Method) at java.util.Arrays.copyOfRange(Arrays.java:3210) at java.lang.String .(String.java:215) 在 java.lang.StringBuilder.toString(StringBuilder.java:430) 在 Solution.findNcr(Solution.java:31) 在 Solution.findNcr(Solution.java:35)
代码:
private static HashMap<String,BigInteger> hm =
new HashMap<String,BigInteger>(10000000,0.9f);
private static BigInteger findNcr(int n, int r) {
BigInteger topLVal = BigInteger.valueOf(0);
BigInteger topRVal = BigInteger.valueOf(0);
int parentN = 0, parentR = 0;
if( r >= n-r) //ncr = nc(n-r)
r = n-r;
if (r == 0 || r == n)
return BigInteger.valueOf(1L);
else if (r == 1 || r == n-1)
return BigInteger.valueOf(n);
else if (hm.containsKey(""+n+""+r)) { //line 31
return hm.get(""+n+""+r);
} else{
parentN = n-1; parentR = r-1;
topLVal = findNcr(parentN, parentR);
topRVal = findNcr(parentN, r);
hm.put(""+parentN+""+parentR,topLVal);
hm.put(""+parentN+""+r, topRVal);
return topLVal.add(topRVal); //line 35
}
}