c - 显示没有连续 1 的二进制字符串

标签 c algorithm recursion dynamic-programming backtracking

我如何修改下面用于显示所有 N 位二进制数组合的回溯代码显示没有连续 1 的二进制数? 例子: 输入:N = 2 输出:3 //3 个字符串分别是 00, 01, 10

输入:N = 3 输出:5 //5 个字符串分别是 000, 001, 010, 100, 101

#include <stdio.h>

char target[100];
void foo(int size, int count)
{
    if (count > size)
        return;
    if (count == size) {
        target[count] = '\0';
        printf("%s\n", target);
        return;
    }
    if (count < size) {
        target[count] = '1';
        foo(size, count+1);
    }
    target[count] = '0';
    foo(size, count+1);
}

int main()
{
    int n = 3;
    foo(n, 0);
    return 0;
}

最佳答案

如果前一个位置也是“1”,则不要放置“1”。例如:

if (count == 0 || target[count-1] != '1') {
    target[count] = '1';
    foo(size, count+1);
}

关于c - 显示没有连续 1 的二进制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28523346/

相关文章:

c - 我用 C 编写了一个简单的程序来计算数字的阶乘

c - C语言Windows下的IP地址和Socket.h

c++ - 私有(private) C++ 成员函数与 C 函数

algorithm - 众所周知的二进制 (WKB) 到十进制纬度/经度

java - 从一组中找出浪费最少的数字

java - 反转字符串的调用堆栈使用递归

c - 返回值 NULL 和零之间的差异

javascript - 简单多边形中 2 个顶点的可见性

algorithm - 树标记算法的复杂性

python - 为什么在计算数组的子集时,变量名称似乎有所不同?