![](/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.