"""
輸入乙個字串,列印出該字串中字元的所有排列。
如輸入abc,則列印出abc、acb、bac、cab、cba
"""class
solution
:def
permutation
(self, s)
:if s ==
none
:return
iflen
(s)==1:
return
list
(s)else
: result =
a = s[-1
]for i in self.permutation(s[:-
1]):
for j in
range
(len
(i)+1)
::j]
+ a + i[j:])
result =
list
(set
(result)
) result.sort(
)return result
defpermutation1
(self, ss):if
notlen
(ss)
:return
iflen
(ss)==1
:return
list
(ss)
charlist =
list
(ss)
charlist.sort(
) pstr =
for i in
range
(len
(charlist)):
if i >
0and charlist[i]
== charlist[i-1]
:continue
temp = self.permutation1(
''.join(charlist[
:i])+''
.join(charlist[i+1:
]))for j in temp:
+ j)
return pstr
# 擴充套件習題,生成字元的所有組合
# 比如輸入abc,則他們的組合有['a', 'ab', 'abc', 'ac',
# 'b', 'bc', 'c'],ab和ba屬於不同的排列但屬於乙個集合
defgroup
(self, ss):if
notlen
(ss)
:return
iflen
(ss)==1
:return
list
(ss)
charlist =
list
(ss)
charlist.sort(
) pstr =
for i in
range
(len
(charlist)):
)if i >
0and charlist[i]
== charlist[i-1]
:continue
temp = self.group(
''.join(charlist[i+1:
]))for j in temp:
+ j)
pstr =
list
(set
(pstr)
) pstr.sort(
)return pstr
if __name__ ==
'__main__'
: ss =
'abc'
s = solution(
)print
(s.permutation1(ss)
)print
(s.group(ss)
)
劍指offer Python3版 五
q 輸入乙個整數陣列,實現乙個函式來調整該陣列中數字的順序,使得所有的奇數字於陣列的前半部分,所有的偶數字於陣列的後半部分,並保證奇數和奇數,偶數和偶數之間的相對位置不變。你要是這樣寫 class solution def reorderarray self,list1 evenlist,oddli...
劍指offer Python3版 九
q 請實現 copyrandomlist 函式,複製乙個複雜鍊錶。在複雜鍊錶中,每個節點除了有乙個 next 指標指向下乙個節點,還有乙個 random 指標指向鍊錶中的任意節點或者 null 思路 複製鍊錶 cur a b c cloned a b c 複製的鍊錶依次加到原煉表後 a a b b ...
劍指offer Python版 替換空格
問題1 替換字串,是在原來的字串上做替換,還是可以重新定義乙個字串做替換 問題2 從前往後替換和從後往前替換一樣嗎?從左往右遍歷元素,若當前元素為空格,則插入 20 並將字串長度增加3.時間複雜度o n n coding utf 8 class solution s 源字串 def replaces...