How do I write a generic memoize function?

后端 未结 15 1745
情话喂你
情话喂你 2020-12-09 05:25

I\'m writing a function to find triangle numbers and the natural way to write it is recursively:

function triangle (x)
   if x == 0 then return 0 end
   retu         


        
15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 06:04

    Please don't recurse this. Either use the x*(x+1)/2 formula or simply iterate the values and memoize as you go.

    int[] memo = new int[n+1];
    int sum = 0;
    for(int i = 0; i <= n; ++i)
    {
      sum+=i;
      memo[i] = sum;
    }
    return memo[n];
    

提交回复
热议问题