Блог пользователя VibhuSpeediest

Автор VibhuSpeediest, история, 16 часов назад, По-английски

If I've written a function with a void return type and want to memoize it, how should I implement it?

void rec(int i, int flag, int sum, int& maxi, int n, vector<int>& arr, int count) {
        if (i == n) {
            if (count <= 4) {
                maxi = max(maxi, sum);
            }
            return;
        }
        if (flag) {
            rec(i + 1, 0, sum - arr[i], maxi, n, arr, count + 1);
            rec(i + 1, 1, sum, maxi, n, arr, count);
        } else {
            rec(i + 1, 1, sum + arr[i], maxi, n, arr, count + 1);
            rec(i + 1, 0, sum, maxi, n, arr, count);
        }
    }

How can I memoize this code?

  • Проголосовать: нравится
  • +3
  • Проголосовать: не нравится

»
11 часов назад, # |
  Проголосовать: нравится +12 Проголосовать: не нравится

Put this at the beginning of your function.

if (visited[i][flag][sum][count])
  return;
visited[i][flag][sum][count] = 1;
  • »
    »
    2 часа назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Won't it consume too much memory since a 4D array is being declared?

    • »
      »
      »
      2 часа назад, # ^ |
      Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

      If this is the case, you could treat the four variables together as an array and hash it, then define visited as an unordered_set.