字母异位词
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次
示例 1: 输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
代码
strs = ["eat", "tea", "tan", "ate", "nat", "bat"] def recurtion(results,temp,nums): if len(nums)==2: results.add(''.join(temp+[nums[0]]+[nums[1]])) results.add(''.join(temp+[nums[1]]+[nums[0]])) if len(nums)>2: for it in range(len(nums)): recurtion(results,temp+[nums[it]],nums[0:it]+nums[it+1:]) def test(nums): #实现nums的全排例 results=set() for it in range(len(nums)): temp=[] temp.append(nums[it]) recurtion(results,temp,nums[0:it]+nums[(it)+1:]) return results results=list() for it in strs: if set(test(it))&set(strs) not in results: results.append(set(test(it))&set(strs)) for it in range(len(results)): results[it] = list(results[it]) print(results)
输出:[['tea', 'ate', 'eat'], ['tan', 'nat'], ['bat']]