Offer Penalty for prove safety (xxvii): alignment of the string

Offer Penalty for prove safety (xxvii): alignment of the string

Search micro-channel public number: 'AI-ming3526' or 'this small computer vision' for more algorithms, machine learning, dry
CSDN: https://blog.csdn.net/baidu_31657889/
GitHub: https://github.com/ aimi-cn / AILearners

First, the primer

This series is my brush "to prove safety Offer" brush off the cattle in question notes online, it aims to enhance the ability under its own algorithm.
View the complete algorithm to prove safety issues resolved Offer Click CSDN and github link:
prove safety Offer complete analytical exercises CSDN address
github address

Second, the title

A string input, prints out all permutations of the characters in the string in lexicographic order. For example input string abc, abc print all strings of characters a, b, c can be arranged out, acb, bac, bca, cab and cba.

Enter a description:

Enter a string of not more than 9 (possibly repeated characters), characters include only lowercase letters.

1, ideas

Recursion, the first fixed problem into the first character, the remaining characters are arranged request; when evaluated with the remaining characters are arranged as the original problem.

(1) traverse all possible position appears in the first character (ie: the first character sequentially exchanged with all subsequent characters);

(2) fixing the first character, character seeking arranged behind (i.e.: during traversal of Step 1, insert implemented recursively).

2, programming

python

Code implementation:

# -*- coding:utf-8 -*-
class Solution:
    def Permutation(self, ss):
        # write code here
        if len(ss) <=1:
            return ss
        res = set()
        #  遍历字符串,固定第一个元素,第一个元素可以取a,b,c...,然后递归求解
        for i in range(len(ss)):
            # 使用排序算法 字符串是除了固定的那个字符 依次固定了元素,其他的全排列(递归求解)
            for j in self.Permutation(ss[:i] + ss[i+1:]):
                # 集合添加元素的方法add(),集合添加去重(若存在重复字符,排列后会存在相同,如baa,baa)
                res.add(ss[i] + j)
        # sorted()能对可迭代对象进行排序,结果返回一个新的list
        return sorted(res)

AIMI-CN AI learning exchange group [1015286623] for more information on AI

Sharing technology, fun in life: our number of public computer vision this small push "AI" series News articles per week, welcome your interest!

Guess you like

Origin www.cnblogs.com/aimi-cn/p/11454412.html