剑指offer——按字典顺序输出字符串的排列

很多算法题对于Python来说,感觉都可以用封装解决。其实若按照c++一步一步来进行,有时候也失去了Python便利的意义。(反正我没在答案里找到。)
基本思路都是用先把可能的排列找出来,在sorted。

class Solution:
	def Permutation(self,ss):
		res=[]
		if len(ss)<2:
			return ss.split()
		for i in range(len(ss)):
			for n in map(lambda x:x+ss[i],self.Permutation(ss[:i]+ss[i+1:])):
			#除第i位置的元素,列出排列组合,递归运算
				if n not in res:
					res.append(n)
		return sorted(res)
		

一直不太会使用lambda,map就把他分解按照下面的代码,不过好像编译不过。
尴尬— —!

for i in range (len(ss)):
	x=self.Permutation(ss[:i]+ss[i+1:])
	x=x+ss[i]
	for n in x

猜你喜欢

转载自blog.csdn.net/weixin_40732844/article/details/82752944
今日推荐