I'm using recursion to solve the problem. On paper my answer should work so I went wrong with the code. However, I can't figure exactly where the problem is.
public class Partition {
public static void main(String[] args) {
System.out.println(part(6,4));
}
public static int part(int n, int m) {
if (n==0) {
return 1;
}
else if(m == 0 || n<0) {
return 0;
}
else {
return part(n-m, m) part(n, m);
}
}
}
CodePudding user response:
You need to reduce m
only for the problem to return 9 as you indicated.
public static int part (int n, int m) {
if (n == 0) {
return 1;
} else if (m == 0 || n < 0) {
return 0;
} else {
return part(n - m, m--) part(n, m);
}
}
CodePudding user response:
I'm not sure what you're trying to do, but if it is to compute the combination it should look like this :
public static int part(int n, int m) {
if(m>n) { //This prevent a wrong input from the user
return part(m, n);
} else if (m==0 || m==n) { //This is your base case
return 1;
} else if(m < 0 || n<0) { //this should not happened, but you never know
return 0;
} else { //this is where you're making mistake(s)
//I don't know if I'm using the formula you are looking for
//But if not, make sure yours do not use part(n, m) otherwise it will run forever
return part(n-1, m) part(n-1, m-1);
}
}