【剑指offer】字符串的排列(python)

1. 数组转字符串
图片说明
字符串转数组,list(str),直接通过list转换时是以每一个字符为分割的。
2. 注意保证不重复
3. 回溯注意局部状态

mark[i] = True
s.append(chars[i])
self.backTravesal(chars, mark, s)
s.pop(-1)
mark[i] = False

这里表示将当前字符的标志置为True,遍历其余字符,最后还需要将字符弹出,清除标志,进行下一次遍历。

# -*- coding:utf-8 -*-
class Solution:
    ret = []
    def Permutation(self, ss):
        # write code here
        if not ss: return None
        chars = list(ss)
        chars.sort()
        mark = [False for i in range(len(chars))]
        self.ret = []
        s = []
        self.backTravesal(chars, mark, s)
        return self.ret
    def backTravesal(self, chars, mark, s):
        if len(s) == len(chars): 
            self.ret.append(''.join(s))
            return
        for i in range(len(chars)):
            if mark[i]: continue
            if i != 0 and chars[i]==chars[i-1] and not mark[i-1]: continue
            mark[i] = True
            s.append(chars[i])
            self.backTravesal(chars, mark, s)
            s.pop(-1)
            mark[i] = False