美文网首页北美程序员面试干货
LintCode 10 [String Permutation

LintCode 10 [String Permutation

作者: Jason_Yuan | 来源:发表于2016-07-12 16:50 被阅读182次

原题

给出一个字符串,找到它的所有排列,注意同一个字符串不要打印两次。

样例
给出 "abb",返回 ["abb", "bab", "bba"]。
给出 "aabb",返回["aabb", "abab", "baba", "bbaa", "abba", "baab"]。

解题思路

  • 思路跟 Permutation II 完全一样

完整代码

class Solution:
    # @param {string} str a string
    # @return {string[]} all permutations
    def stringPermutation2(self, strs):
        # Write your code here
        if strs is None:
            return []
        res = []
        flags = [False] * len(strs)
        self.helper(sorted(strs), flags, "", res)
        return res
        
    def helper(self, strs, flags, path, result):
        if len(path) == len(strs):
            result.append(path)
            return
        
        for i in range(len(strs)):
            if not flags[i]:
                if i != 0 and not flags[i - 1] and strs[i] == strs[i - 1]:
                    continue
                flags[i] = True
                self.helper(strs, flags, path + strs[i], result)
                flags[i] = False

相关文章

网友评论

    本文标题:LintCode 10 [String Permutation

    本文链接:https://www.haomeiwen.com/subject/zkcsjttx.html