js递归求和1,2,3,..., n,..., 3,2,1?

js递归求和1,2,3,..., n,..., 3,2,1?

海绵宝宝撒
浏览 965回答 5
5回答

慕尼黑的夜晚无繁华

答案楼上其实都有了,然而题目要求递归,递归吧,我的理解呢,就是尽量避免什么转化过程,尽量少动脑吧?我就主要说说解这种题的思路吧。递归的思路就是分阶段求解,然后定终点。核心就是找fn(n)和fn(n-1)的关系,结合边界条件fn(1),写出一个如下的函数:function fn(n) {    // 终点    if (...) return ...;    // 递归    return fn(n-1) + ...;}以本题来说,fn(n) = 1 + 2 + 3 + ... + n-1 + n + n-1 + ... + 3 + 2 + 1;fn(n-1) = 1 + 2 + 3 + ... + n-1 + ... + 3 + 2 + 1;故fn(n) = fn(n-1) + n-1 + n;终点fn(1) = 1;结合便能写出function fn(n) {    if (n==1) return 1; // 终点    return fn(n-1) + n-1 + n; // 递归关系}类似的就同理可得咯

慕斯709654

定义f(n) = sum(1, 2, 3, ..., n, ..., 3, 2, 1)。解法一问题转化为f(n) = 2 * g(n) - n,其中g(n) = sum(1, 2, 3, ..., n)。不用高斯求和法强行递归的话,g(n) = g(n - 1) + n(n > 1),g(n) = 1(n = 1)。function g(n) {  if(n > 1) return g(n - 1) + n;  else if(n == 1) return 1;}function f(n) {  return 2 * g(n) + n;}解法二显然,f(n) = f(n - 1) + n + (n - 1)(n > 1),f(n) = 1(n = 1)。function f(n) {  if(n > 1) return f(n - 1) + n + n - 1;  else if(n == 1) return 1;}

慕少森

var a = 1;for (var i = 2; i < n; i++) {&nbsp; &nbsp; a = a + i}var sum = 2*a + n;console.log(sum)

墨色风雨

将1,2,3,..., n,..., 3,2,1转化为求前n项的和与前n-1的和的和。于是有了:1 + 2 + 3 + 4 + ... + n + ... + 3 + 2 + 1 = n(n + 1)/2 + (n - 1)(n - 1 + 1)/2&nbsp;整理得到 n2所以:Math.pow(n, 2)但是题目又要求用递归做。const cal = (n) => {&nbsp; if(n === 1) {&nbsp; &nbsp; return 1;&nbsp; }&nbsp; return 2 * n + cal(n - 1) - 1;}console.log(cal(4)) //16

Qyouu

不用数学的思想 单纯用递归的思想&nbsp;比如传入4先执行先序递归 index++先序递归做value = 1+2+3+4&nbsp;满足条件后 return;然后执行后续递归 开始index--后续递归做value += 3+2+1+0;var cal = function() {&nbsp; &nbsp; &nbsp; &nbsp; var index=0;&nbsp; &nbsp; &nbsp; &nbsp; var value=0;&nbsp; &nbsp; &nbsp; &nbsp; return function show(n) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(n < 0) return;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value += index;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(index === n)return;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; index++;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; show(n);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; index--;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value += index;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return value;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };&nbsp; &nbsp; cal()(4) // 16&nbsp; &nbsp;&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript