Title Description
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:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
This question we put it another thought, assuming the title to all of the string is not repeated letters , and then ask us to the subject of several string arrangement given, this time we had an arrangement should be able to think of using a combination of ways to solve this Road title.
First, we assume the position of four letters four cups, assuming four letters ABCD , the possibility of a cup is placed first four letters (A, B, C, D ), three second cup because the first cup has been identified with a letter, so that the second cup to three options, and so on, there are two third cup, there is a fourth cup
\ [4 * 3 * 2 * 1 = 24 \]
Therefore, a total of 24 possibilities. However, we give the title claim particular arrangement, and may have duplicate strings of letters, we can understand the combination of the above arrangement, we give a specific manner according to the alphabetical.
For example, assuming a title string is ABCD , we can use the first letter in the alphabet are four positions like exchange of a derived position of the first letter:
\ [ABCD, BACD, CBAD, the DBCA \ ]
as we have come to four, then we need to consider what position is the second letter, due to excessive kind, here only ABCD, for example (the remaining three empathy):
\ [ABCD, ACBD, ADCB \]
as we have come to three, and then decide what the next letter is the fourth position, the reasons above, we only ABCD For example:
\ [ABCD, ABDC \]
as we have come to two, then the next we do not see the need, and the fourth position there is only a possibility.
If you understand the above derivation, the next part of the code should be able to read the
function Permutation(str)
{
// 判空操作
if(str.length==0){return [];}
const letters = str.split('');
let res = [];
function perm(list, start){
if(start === letters.length-1){
const str = list.join('');
// 有可能会有重复字母,所以做查重处理
if(!res.includes(str)){
res.push(str);
}
}
for(let i=start; i<list.length; i++){
[list[i], list[start]] = [list[start], list[i]];
perm(list, start+1);
// 还原原有列表排序,以免影响后续计算
[list[i], list[start]] = [list[start], list[i]];
}
}
perm(letters, 0);
// 按照字典序排序输出
return res.sort((a,b)=>{return a>b?1:-1});
}