algorithm - 描述一种递归算法来打印所有不包含任何连续 1 的 N 位二进制字符串
问题描述
我找到了一个给出连续 1 的解决方案,但我找不到二进制字符串中不包含连续 1 的任何内容,有人可以帮我吗?
解决方案
从空字符串递归。在每次调用时,决定在基本字符串的最后一个字符上附加什么。当字符串达到所需大小时终止。
def recurse(base,n):
#termination criteria
if len(base)==n:`
print(base)
#You can add '0' or '1' if the base string ends with '0' or is empty
#and recurse. There is no issue having consecutive zeroes.
elif base== "" or base[-1]=="0" :
recurse(base+"0",n)
recurse(base+"1",n)
#To prevent consecutive '1's, append '0' only to the base string ending
#with '0'
elif base[-1]=="1":
recurse(base+"0",n)
n=int(input())
recurse("",n)
对于 n=5,输出为:
00000 00001 00010 00100 00101 01000 01001 01010 10000 10001 10010 10100 10101
推荐阅读
- reactjs - (替换 & 之间有什么区别
) 在反应路由器中 - android - RecognitionService:在没有RECORD_AUDIO权限的情况下调用识别服务;扩展识别服务
- typescript - 嵌套映射类型必须实现子索引的所有模式吗?
- python - EMR 的 Boto3 API 不支持“OnDemandPrice”
- google-colaboratory - 在 Google Colab 上进行 cs231 作业时出错
- typescript - 打字稿调用签名
- pseudocode - 绘制/编写流程图/伪代码
- javascript - 在哪里可以检查开发工具上的 Javascript 的 JSON.parse() 错误日志?
- mysql - 在 MySql 中,如何检查具有 json 字段的行是否具有包含特定文本的键?
- highcharts - Highcharts 绘制 MACD + EMA + 交易量