【发布时间】:2022-01-11 10:35:39
【问题描述】:
我正在尝试自己学习递归,并且遇到了一个练习,要求:“编写一个递归函数来确定数组是否为回文,其中数组及其大小作为参数给出。如果返回 1 a[] 是回文,否则为 0。”
我已经尝试了很多东西,但我的代码仍然无法正常工作。我正在访问最后一段代码中的 console.log 检查,但 x、y 和 stepsLeft 变量似乎没有更新。 (警告:)因此,代码是一个未闭合的循环,并且超出了最大调用堆栈大小或代码无限递归。帮忙修一下?
function isPalindrome(arr, size) {
var stepsLeft;
var x;
var y;
// initialize variables that will change in subsequent calls
if (stepsLeft === undefined) {
var hold = size / 2;
stepsLeft = Math.floor(hold);
x = 0;
y = size - 1;
}
logged = console.log(stepsLeft);
//base case: if you go through all steps towards the center and everything matches, return true
if (stepsLeft === 0) {
return 1;
}
//recursion cases
if (arr[x] !== arr[y]) {
// if the x and y EVER don't match, return false.
return 0;
}
//increase the x and decrease the y, and check again
x++;
y--;
stepsLeft--;
console.log("here");
return isPalindrome(arr, size);
}
【问题讨论】:
-
传递给
isPalindrome的参数(arr,size)实际上从未改变,因此每次调用isPalindrome时,它的运行方式完全相同。为了使递归工作,您需要解决部分问题,然后调用isPalindrome处理较小的剩余问题。
标签: javascript debugging recursion