[英]How do you recursively count the number of negative numbers in an array (Java)?
[英]How to recursively count the number of possible increasing sequences from x consecutive numbers?
令 integer x
為數字組合的長度,並讓連續整數的范圍從 1 到max
。 序列必須是非遞減的(序列通常是遞增的,但相同的連續數字是可能的)。 給定x
和max
多少個這樣的序列是可能的?
例如,對於x
=3, max
= 2,有 4 個可能的序列:
1,1,1
1,1,2
1,2,2
2,2,2
我想到了以下遞歸方法:
public static int howManySorted(int n, int max, int len, int i) {
if(len > n || i > max) {
return 0;
}
if(len == n && i == max) {
return 1;
}
return howManySorted(n, max, len + 1, i + 1) +
howManySorted(n, max, len + 1, i) +
howManySorted(n, max, len, i + 1);
}
howManySorted(n, max, len + 1, i + 1)
是指序列長度加一,下一個數比前一個大一的情況。
howManySorted(n, max, len + 1, i)
是指序列長度加一,下一個數與前一個數相同的情況。
我確實意識到我的遞歸公式存在問題,因為在這樣的序列中,相鄰數字之間的差異最多為1
。 所以我決定添加另一個調用howManySorted(n, max, len, i + 1)
來彌補這種情況,但這仍然不會產生預期的結果。 我究竟做錯了什么?
我像這樣從main
調用這個方法howManySorted(n, max, 1, 1)
。
假設len = 10
和max = 5
。
請注意,由於我們對實際解決方案不感興趣,只對計數感興趣,因此范圍 2-5 的結果與范圍 1-4 的結果相同。
對於第一個數字,我們可以選擇一個數字 1-5,然后:
len = 9
遞歸調用,將數字范圍限制為 1-5,即max = 5
len = 9
遞歸調用,將數字范圍限制為 2-5,即max = 4
len = 9
遞歸調用,將數字范圍限制為 3-5,即max = 3
len = 9
遞歸調用,將數字范圍限制為 4-5,即max = 2
len = 9
遞歸調用,將數字范圍限制為 5-5,即max = 1
總結遞歸調用返回的計數。 這就是這個調用的結果。
當len = 1
,有max
解,因此返回max
作為計數。
當max = 1
,無論len
為何,都只有一個解,因此返回1
作為計數。
我會把實際的編碼留給你。
public static int howManySorted(int n, int max)
{
return howManySorted(n, 1, max);
}
private static int howManySorted(int n, int min, int max)
{
if (n == 1)
return max - min + 1;
if (min == max)
return 1;
return howManySorted(n, min + 1, max) + howManySorted(n-1, min, max);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.