使用递归创建CountdownPassed(JS算法)



问题

我们用一个参数(n(定义了一个叫做倒计时的函数。函数应使用递归返回一个数组,该数组包含基于n参数的整数n到1。如果用小于1的数字调用函数,则该函数应返回一个空数组。例如,当n=5时调用此函数应返回数组[5,4,3,2,1]。函数必须通过调用自身来使用递归,并且不能使用任何类型的循环。

function countdown(n, newArr = []){

if(n == 1){
return newArr;
}
newArr.push(n);
return countdown(n - 1)
}
console.log(countdown(5));

我的问题

有没有办法修复这个代码,使其正常工作

我可以提供另一种解决方案,但我不理解:

function countdown(n) {
if (n < 1) {
return [];
} else {
const arr = countdown(n - 1);
arr.unshift(n);
return arr;
}
}

问题是没有将数组传递给递归调用,因此每次递归执行都会创建一个新的空数组。因此,它不会返回推送了值的数组,而是从递归调用返回的新的空数组。

其次,永远不要将值1推送到数组中。因此,最好将递归停止在0而不是1。

因此,采取这两个修复,你会得到:

function countdown(n, newArr=[]) {
if (n <= 0) {
return newArr;
}
newArr.push(n);
return countdown(n - 1, newArr)
}
console.log(countdown(5));

您的替代解决方案是干净的,因为它不需要将数组作为参数传递。它使用返回的数组向其添加下一个值(在其前面(。这是我的偏好。

要了解它是如何工作的,请打印出中间值:

function countdown(n) {
if (n < 1) {
console.log("At the end of recursion. Creating and returning an empty array.");
return [];
} else {
const arr = countdown(n - 1);
console.log("Got the following array back from the recursive call:");
console.log(JSON.stringify(arr));
arr.unshift(n);
console.log("Prefixing it with " + n + " and returning the result:");
console.log(JSON.stringify(arr));
return arr;
}
}
var result = countdown(5);

是的,您可以像一样修改您的解决方案

function countdown(n){

if(n == 0){
// stop the function at 0 so it will not be included in the array
return [];
}

// concat the value of n as an array with the value less than it
return [n].concat(countdown(n - 1))
}


console.log(countdown(5));

解决方案中的问题是,每次将数组初始化为空数组,因此最终的答案将是空数组

您需要为递归调用移交结果数组。您需要检查是否没有剩余值,十返回结果数组。

function countdown(n, result = []) {
if (n < 1) return result;
result.push(n);
return countdown(n - 1, result);
}
console.log(countdown(5));

作为另一种方法,您可以返回一个数组,对于退出条件,取最终值,否则取n和递归调用的扩展结果。

function countdown(n) {
if (n < 1) return [];
return [n, ...countdown(n - 1)];
}
console.log(countdown(5));

此时,我们将创建倒计时函数,该函数调用自己并称为递归。

function countdown(n) {
if (n < 1) {
return [];
} else {
console.log(n, "before calling");
const arr = countdown(n - 1);
console.log(n, "after calling");
return arr;
}
}
console.log(countdown(5));

现在,当我们知道";在呼叫";是n减少的地方;在呼叫"之后;是n增加的地方,在此基础上我们可以这样做。

const arr = [];
function countdown(n) {
if (n < 1) {
return arr;
} else {
arr.push(n);
return countdown(n - 1);;
}
}
console.log(countdown(5));

最新更新