【问题标题】:display binary strings without consecutive 1’s显示没有连续 1 的二进制字符串
【发布时间】:2015-04-15 21:31:12
【问题描述】:

如何修改以下用于显示所有 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;
}

【问题讨论】:

  • @ChiefTwoPencils:修改为不显示连续的 1,如示例所示。对于 N=3:000、001、010、100、101
  • 啊,明白了!擦除以前的 cmets....

标签: c algorithm recursion dynamic-programming backtracking


【解决方案1】:

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

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

【讨论】:

  • 谢谢,它就像一个魅力。我记得我确实尝试过这个,但不知何故我忽略了结果并认为它不起作用。谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-17
  • 2019-09-13
  • 1970-01-01
  • 2017-05-20
相关资源
最近更新 更多