python 字符串排列dfs

字符串的排列

http://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7

题目描述

输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。

思路:dfs

定义一个set保持在当前位置已经访问过的字符

class Solution:
    def Permutation(self, s):
        def bfs(visited, unvisited):
            if len(unvisited) == 0:
                res.append(visited)
                return 
            d = set()
            for i, x in enumerate(unvisited):
                if x not in d:
                    d.add(x)
                    bfs(visited+x, unvisited[:i]+unvisited[i+1:])

        res = []
        bfs('', s)
        return res

print(Solution().Permutation('aab'))
全部评论

相关推荐

卓望数码 Java开发岗 总包23+1~2福利补贴,公积金12%
点赞 评论 收藏
转发
投递海康威视等公司10个岗位
点赞 评论 收藏
转发
3 1 评论
分享
牛客网
牛客企业服务