請幫助我理解以下代碼如何始終回傳陣列中的最小值。我嘗試移動 3 的位置,但無論它在陣列中的位置如何,它總是設法回傳它。
let myA = [12,3,8,5]
let myN = 4
function F4(A,N)
{
if(N==1){
return A[0]
}
if(F4(A,N-1) < A[N-1]){
return F4(A,N-1)
}
return A[N-1]
}
console.log(F4(myA,myN))
uj5u.com熱心網友回復:
這很難獲得直覺。學習解決此類問題的程序而不是簡單地告訴答案也非常重要。
如果我們首先查看帶有一些注釋和命名變數的代碼,它看起來像這樣:
let myA = [12,3,8,5];
let myN = myA.length;
function F4(A, N) {
// if (once) there is only one element in the array "A", then it must be the minimum, do not recurse
if (N === 1){
return A[0]
}
const valueFromArrayLessLastEl = F4(A,N-1); // Goes 'into' array
const valueOfLastElement = A[N-1];
console.log(valueFromArrayLessLastEl, valueOfLastElement);
// note that the recursion happens before min(a, b) is evaluated so array is evaluated from the start
if (valueFromArrayLessLastEl < valueOfLastElement) {
return valueFromArrayLessLastEl;
}
return valueOfLastElement;
}
console.log(F4(myA, myN))
并產生
12 3 // recursed all the way down
3 8 // stepping back up with result from most inner/lowest recursion
3 5
3
但是為了獲得洞察力,通過考慮最簡單的情況并從那里擴展來解決問題是至關重要的。如果我們寫的情況下,代碼會發生什么N = 1和N = 2:
// trivially take N=1
function F1(A) {
return A[0];
}
// take N=2
function F2(A) {
const f1Val = F1(A); // N-1 = 1
const lastVal = A[1];
// return the minimum of the first element and the 2nd or last element
if (f1Val < lastVal) {
return f1Val;
}
return lastVal;
}
請注意,陣列沒有被修改,我說好像是因為N每次遞回時的值都會遞減。
WithmyA = [12, 3, 8, 5] F1將始終回傳 12。F2將這個值 12 與第 n-1 個元素的值 3 進行比較,并回傳最小值。
如果您可以在此基礎上計算出F3會做什么,那么您可以從那里進行推斷。
Play around with this, reordering the values in myA, but crucially look at the output as you increase N from 1 to 4.
As a side note: by moving the recursive call F4(A,N-1) to a local constant I've prevented it being called twice with the same values.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/334910.html
標籤:递归
下一篇:我在遞回函式中沒有得到任何輸出
