49. 字母异位词分组

Python递归实现全排列

49. 字母异位词分组

 思路:将字符串按字母顺序排列,之后相同的放到同一个list下面。

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        rs = []
        di = dict()
        index = 0
        for str in strs:
            tmp = []
            for char in str:
                tmp.append(char)
            ans = "".join(sorted(tmp))
            # print(ans)
            if ans in di:
                # di[ans] += 1
                # 这里rs的下标怎么弄? 字典的value是返回list的index.
                # rs[0].append(str) [['eat', 'tea', 'ate', 'nat'], ['tan'], ['bat']]
                rs[di[ans]].append(str)
            else:
                di[ans] = index
                rs.append([str])
                index += 1
            # print(di)
            # print(rs)
        return rs