"Rolling Array" --- Rolling array idea, used in dynamic programming

Rolling array is a programming idea in DP. The simple understanding is to make the array scroll up and use a fixed number of storage spaces each time to achieve compression and save storage space. Play an optimization space, mainly used in recursive or dynamic programming (such as 01 knapsack problem). Because the DP problem is a bottom-up expansion process, we often need to use continuous solutions, and the previous solutions can often be discarded. So it is very effective to optimize with rolling array. Using a rolling array can achieve the effect of compressed storage when N is large.

Of course it's time to change space

Give a simple example

Fibonacci sequence:

#include<stdio.h>
int main()
{
    
    
    int i;
    long long d[80];
    d[0]=1;
    d[1]=1;
    for(i=2;i<80;i++)
    {
    
    
        d[i]=d[i-1]+d[i-2];
    }
    printf("%lld\n",d[79]);
    return 0;
}

The above loop d[i] only depends on the first two data d[i-1] and d[i-2]; in order to save space, a rolling array is used.

#include<stdio.h>
int main()
{
    
    
    int i;
    long long d[3];
    d[1]=1;
    d[2]=1;
    for(i=2;i<80;i++)
    {
    
    
        d[0]=d[1];
        d[1]=d[2];
        d[2]=d[0]+d[1]; 
    }
    printf("%lld\n",d[2]);
    return 0;
}

Another form of expression

#include<stdio.h>
int main()
{
    
    
    int i;
    long long d[3];
    d[0] = 1;
    d[1] = 1;
    for(i=2;i<80;i++)
    {
    
    
    	d[i%3]=d[(i-1)%3]+d[(i-2)%3];
    }
    printf("%lld\n",d[79%3]);
    return 0;
}

Two-dimensional array example

int i, j, d[100][100];
for(i = 1; i < 100; i++)
    for(j = 0; j < 100; j++)
        d[i][j] = d[i - 1][j] + d[i][j - 1];

The above d[i][j] only depends on d[i-1][j], d[i][j-1];
use rolling array

int i, j, d[2][100];
for(i = 1; i < 100; i++)
    for(j = 0; j < 100; j++)
        d[i % 2][j] = d[(i - 1) % 2][j] + d[i % 2][j - 1];

Reprinted from: https://blog.csdn.net/weixin_40295575/article/details/80181756

Guess you like

Origin blog.csdn.net/weixin_42692164/article/details/113859151