简体   繁体   中英

Bit-string without consecutive 1's, using Top-down DP

count all distinct binary strings without two consecutive 1's

I tried to convert bottom-to-top dynamic programming approach( mentioned in the link ) to recursive relation but could not able to get the correct output.

#include<iostream>
#define n 4
using namespace std;


int bitstring(int N, int b = 0)
{
    static int s = 0;
    //termination condition
    if (N == 1)
        return 1;
    if(b == 1)
    {
        s += bitstring(N - 1, 0);
    }
    if (b == 0)
    {
        s = bitstring(N - 1, 0) + bitstring(N - 1, 1);
    }
    return s;
}

int main()
{
    cout << bitstring(n) << endl;
    return 0;
}

for N = 3 output is 5

illustration for N=3

                f(3,0)        f(3,1)
                /     \          |
            f(2,0)  f(2,1)     f(2,0)
            /   \      |       /     \
        f(1,0) f(1,1) f(1,1)  f(1,0)  f(1,1)
          |      |       |      |        |
          1      1       1      1        1

At least for case N==1 you have two sequences [0] and [1]. May be it is better to start from corner cases ^_^ And for case b==1 and b==0 you are using different manipulations with s , is it should be like that?

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