I am new to Java and am I trying to implement a recursive method for finding "n choose k".
However, I've run into a problem.
public class App {
public static void main(String[] args) throws Exception {
int n = 3;
int k = 2;
int result = combRecursion(n, k);
System.out.println(result);
}
private static int combRecursion(int n, int k) {
if (k == 0) {
return 1;
} else {
return (combRecursion(n - 1, k - 1) + combRecursion(n - 1, k));
}
}
Output: many repetitions of this line:
at App.combRecursion(App.java:14)
Your base case ought to include both
n == k || k == 0for "n choose k" to be implemented correctly. That way, both calls will eventually terminate (even though your current implementation is rather inefficient as it has exponential runtime). A better implementation would use the formulan!/k!/(n-k)!or the multiplicative formula to run in linear time:further optimizing this is left as an exercise to the reader (hint: a single for loop suffices).