【发布时间】:2020-04-14 07:41:00
【问题描述】:
count all distinct binary strings without two consecutive 1's
我尝试将自下而上的动态编程方法(链接中提到)转换为递归关系,但无法获得正确的输出。
#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;
}
对于 N = 3 输出为 5
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
【问题讨论】:
-
一方面,
s = bitstring(N - 1, 0) + bitstring(N - 1, 1)中函数调用的顺序是未指定的,所以either可以先递归调用。 -
@1201ProgramAlarm,总是先执行
bitstring(N-1,0),之后只调用bitstring(N-1,1)。我在调试器上也检查过。 -
这次你可能有正确的顺序,但是不同的编译器(或不同的优化设置)可能会导致顺序改变。另一个问题是静态
s变量的赋值(考虑一下)。
标签: c++ dynamic-programming bitstring