Python 基础知识简单

N位二进制数

“N 位二进制数”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 n_bit_binary(n) ,生成所有 n 位二进制数(作为字符串),使得在二进制字符串的每个前缀中,1 的数量大于或等于 0 的数量。将结果作为按字典顺序排序的字符串列表返回。

约束条件
  • 1 <= n <= 15

示例

Example 1
Input
n = 3
Output
['110', '111']
Explanation

For '110': prefixes '1'(1>=0✓), '11'(2>=0✓), '110'(2>=1✓). For '111': all prefixes have more 1s. '100','101','010' etc. fail the prefix condition.

Example 2
Input
n = 2
Output
['10', '11']
Explanation

'10': prefix '1' has 1>=0✓, '10' has 1>=1✓. '11': both prefixes valid. '00','01' fail.

Example 3
Input
n = 1
Output
['1']
Explanation

Only '1' satisfies the condition. '0' has prefix '0' with 0 ones and 1 zero.

Need a Hint?
考虑使用特定于递归的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。