简体   繁体   中英

Translate this code from recursive to iterative DP

double R(int N, int x[206], int i, int c){
    if (memo[i][c] != 0) return memo[i][c];

    if (i==N){
        if (c>=23) return 1;
        else return 0;
    }

    double s;
    s = R(N,x,i+1,c+x[i]);
    s += R(N,x,i+1,c-x[i]);
    memo[i][c] = s;
    return s;
}

Right now this is a recursive memoized function but I want to translate this to iterative equivalent DP if possible. Or is this the only way I can do it?

In theory, you can convert any recursive method in to an iterative one. So, yes, this code can too.

More about it is in this thread: https://stackoverflow.com/questions/931762/can-every-recursion-be-converted-into-iteration

Since x can contain arbitrary integers, you should really compute R for any value of c where i is fixed. Some code to explain:

// case where i == N
for (int c = INT_MIN; c < INT_MAX; ++c) {
   memo[N][c] = (c>=23) ? 1 : 0;
}

for (int k = N - 1; k >= i; --k) {
  for (int c_ = INT_MIN; c_ < INT_MAX; ++c_) {
     memo[k][c_] = memo[k+1][c_ + x[k]] + memo[k+1][c_ - x[k]];
  }
}
return memo[i][c];

Maybe some restrictions on values of x can help to improve result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM