立即從另一個函數調用一個函數的想法表明了函數自己調用的可能性。 Java中的函數調用機制支持這種可能性,這就是所謂的遞歸。遞歸是一種功能強大的通用編程技術,是許多重要計算應用程序的關鍵,從爲信息處理(第4章)提供基本支持的組合搜索和排序方法方法到信號處理的快速傅里葉變換(第9)。
您的第一個遞歸程序。 遞歸的HelloWorld的是落實階乘函數,這是由方程
N! = N × (N-1) × (N-2) × ... × 2 × 1
N代表正整數N,定義!很容易計算與一個for循環,但在Factorial.java一個更簡單的方法是使用下面的遞歸函數:
public static int factorial(int N) {
if (N == 1) return 1;
return N * factorial(N-1);
}
,它通過注意因子生成所需的結果你能說服自己()返回1 = 1!當n爲1,並且如果正確計算值
(N-1)! = (N-1) × (N-2) × ... × 2 × 1
那麼正確計算值
N! = N × (N-1)! = N × (N-1) × (N-2) × ... × 2 × 1
我們可以跟蹤我們跟蹤的函數調用任何序列以同樣的方式這種計算。
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120
我們的階乘()實現展現了每個遞歸函數所需的兩個主要組件。
The base case returns a value without making any subsequent recursive calls. It does this for one or more special input values for which the function can be evaluated without recursion. For factorial(), the base case is N = 1.
The reduction step is the central part of a recursive function. It relates the function at one (or more) inputs to the function evaluated at one (or more) other inputs. Furthermore, the sequence of parameter values must converge to the base case. For factorial(), the reduction step is N * factorial(N-1) and N decreases by one for each call, so the sequence of parameter values converges to the base case of N = 1.
Now in your case (n==1) is the base condition or terminating condition.
recurse(4,'A','B','C')
recurse(3,'A','C','B')
recurse(2,'A','B','C')
recurse(1,'A','C','B')
return : 1 A C
return : 2 A B
return : 3 A C
return : 4 A B
final output :
1 A C
2 A B
3 A C
4 A B
那麼哪部分是不明確的? – user2864740
該解決方案是, 1 AC 2 AB 3 AC 4 AB 我的問題是當伊特拉婷通過煙囪, 1 ACB 1 ABC 2 ACB N一個二三 我不明白爲什麼b和c不斷來回切換 – user201535
查看方法定義中參數的順序,然後查看方法調用中參數的順序。 (確保包括那種在後/問題的信息/問題)。 – user2864740