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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。