One - One Code All

Blog Content

Lintcode-10:字符串的不同排列

Python 每日一练 算法 LintCode   2010-03-10 18:05:32

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

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

解题思路
思路跟 Permutation II 完全一样

# -*- coding: utf-8 -*-

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

样例
给出 "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



if __name__ == '__main__':
    sol = Solution()
    res = sol.stringPermutation2(strs='abc')
    print(res)

输出:['abc', 'acb', 'bac', 'bca', 'cab', 'cba']


上一篇:Lintcode-9:Fizz Buzz 问题
下一篇:python内置模块logging

The minute you think of giving up, think of the reason why you held on so long.