写这段代码的时候就是不知道在哪里写递归函数,一开始写的是res.append(head+self.Permutation(shadow)),果然递归就是一看就会一写就废

class Solution:
    def Permutation(self, ss):
        # write code here
        if len(ss) == 0:
            return []
        if len(ss) == 1:
            return ss
        res = []
        for i in range(len(ss)):
            head = ss[i]
            shadow = ss[:i]+ss[i+1:]
            for j in self.Permutation(shadow):
                res.append(head + j)
        return sorted(list(set(res)))
  • 一种更好理解的方法:
    class Solution:
      def Permutation(self, ss):
          # write code here
          if not ss:
              return []
          res = []
          def backtrack(nums, tmp):
              if not nums:
                  res.append(tmp)
                  return 
              for i in range(len(nums)):
                  backtrack(nums[:i] + nums[i+1:], tmp + nums[i])
          backtrack(ss, '')
          return sorted(list(set(res)))

leetcode两道道相似的题:
(全排列)https://leetcode-cn.com/problems/permutations/
(电话号码的组合):https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/