![](/img/trans.png)
[英]Count number of pairs of two numbers less than or equal to N such that Sum of the digits of numbers of pair is Prime
[英]Divide a number n into two numbers such that sum of two numbers is n
例如,如果n为4,则n1 + n2 =4。n,n1,n2> = 0
输出应该是
[4, 0] [0, 4] [1, 3] [2, 2] [3, 1]
我试过了。
public static void partition(int n, int x, int y) throws Exception{
int n1, n2;
n1 = x;
n2 = y;
System.out.println(n1 + " : " + n2);
x = x - 1;
y = y + 1;
if ( x >= 0) {
TestMethods.partition(n, x, y);
} else {
return;
}
}
我将上述方法称为TestMethods.partition(4,4,0);
我想看看我可以对该方法进行哪些改进以使其更有效。
我根本不会使用递归。 每个递归调用都将占用堆栈上多余的空间,而您实际上并不需要这些空间。 如果n
大,则可能导致StackOverflowError
。 当然,这取决于您的堆栈大小。 在我的系统上,它抛出了n = 9998的错误。
只需使用一个简单的for
循环。 而且您不需要那些额外的方法参数x
和y
,即IMO。
public static void partition(int n) {
for (int i = n; i >= 0; --i) {
System.out.printf("[%d, %d] ", i, n - i);
}
}
并且只需像调用TestMethods.partition(4);
一样使用它即可
请注意,通过在同一迭代中打印对称输出,可以节省迭代次数。 这会将迭代次数减少到一半:
for (int i = 0; i <= (n + 1) / 2; ++i) {
System.out.printf("[%d, %d] [%d, %d] ", i, n - i, n - i, i);
}
尝试这个
int num=4;
for(int i=0;i<=num;i++){
System.out.println("["+i+","+(num-i)+"]");
}
好吧,如果您必须使用递归,那么您根本就不需要y参数,因为您可以通过从n减去x来获得y,而y = nx。 而且,当x <= nx时,您可以停止递归,以免出现[3,1]和[1,3]之类的重复值
public static void partition(int n, int x) throws Exception{
int n1, n2;
n1 = x; n2 = n - x;
System.out.println(n1 + " : " + n2);
if ( n1 - 1 >= n2 + 1) {
TestMethods.partition(n, n1 - 1);
} else {
return;
}
}
此外,通过删除临时变量n1,n2,可以进一步简化此代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.