topic:
Enter a character string and print out all the permutations of characters in the string in lexicographical order. For example, input the string abc, then print out all the strings abc, acb, bac, bca, cab and cba that can be arranged by the characters a, b and c.
Ideas:
1. Use each character in the string as the first character
2. Fix the first character, each character in the remaining string acts as the second character once
3. Fixed the second character, each character in the remaining string acts as the third character
Recursively ...
Code
1 class Solution:
2 def Permutation (self, ss):
3 if not ss:
4 return []
5 res = []
6 self.perCore (ss, res, '' )
7 return sorted (list (set (res)) ) # used to set weight sorted using the sort in lexicographic order
. 8
. 9 DEF perCore (Self, SS, RES, path):
10 IF Not SS:
. 11 res.append (path)
12 is the else :
13 is for I in Range (len ( ss)):
14 self.perCore(ss[:i] + ss[i+1:], res, path + ss[i])
15 if __name__ == '__main__':
16 str='123'
17 s= Solution()
18 print(s.Permutation(str))
Detailed recursive process
The solid arrow indicates the forward arrow, and the dashed arrow indicates the program rollback process
Reference to other people's code: