Python 基礎知識簡單

列印字串的所有排列

「列印字串的所有排列」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 permutations(s),它接受字串 s 並傳回 s 中字元的所有唯一排列的排序清單。每個排列都是所有字元的重新排列。傳回的列表必須按字典順序(字母順序)排序。

約束條件
  • 1 <= len(s) <= 8
  • s contains only lowercase English letters

範例

Example 1
Input
s = 'abc'
Output
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Explanation

All 3! = 6 rearrangements of 'a', 'b', 'c', sorted alphabetically.

Example 2
Input
s = 'ab'
Output
['ab', 'ba']
Explanation

Two characters give 2! = 2 permutations.

Example 3
Input
s = 'aab'
Output
['aab', 'aba', 'baa']
Explanation

There are only 3 unique permutations since 'a' is repeated.

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

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