题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
解题思路
我们求整个字符串的排列,其实可以看成两步:
第一步求所有可能出现在第一个位置的字符(即把第一个字符和后面的所有字符交换[相同字符不交换]);
第二步固定第一个字符,求后面所有字符的排列。这时候又可以把后面的所有字符拆成两部分(第一个字符以及剩下的所有字符),依此类推。这样,我们就可以用递归的方法来解决。
代码实现
去博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片
.
import java.util.ArrayList;
import java.util.Collections;
public class strPermutation {
//字符串的排列组合
ArrayList<String> res=new ArrayList<>();
public ArrayList<String> permutation(String str){
if (str==null){
return res;
}
permutationHelper(str.toCharArray(),0);
Collections.sort(res);
return res;
}
public void permutationHelper(char[] str,int i){
if (i==str.length-1){
res.add(String.valueOf(str));
}else {
for (int j=i;j<str.length;j++){
if (j!=i&&str[i]==str[j]){
continue;
}
swap(str,i,j);
permutationHelper(str,i+1);
swap(str,i,j);
}
}
}
public void swap(char[] str,int i,int j){
char temp=str[i];
str[i]=str[j];
str[j]=temp;
}
public static void main(String[] args) {
strPermutation test=new strPermutation();
ArrayList<String> res=test.permutation("abc");
System.out.println(res);
}
}
class Solution {
List<String> list=new ArrayList<>();
public String[] permutation(String s) {
if (s==null||s.length()==0){
return null;
}
char[] ch=s.toCharArray();
dfs(ch,0);
return list.toArray(new String[list.size()]);
}
public void dfs(char[] ch,int x){
if (x== ch.length-1){
list.add(String.valueOf(ch));
return;
}
HashSet<Character> set=new HashSet<>();
for (int i=x;i<ch.length;i++){
if (set.contains(ch[i])){
continue;
}
set.add(ch[i]);
swap(ch,i,x);
dfs(ch,x+1);
swap(ch,i,x);
}
}
public void swap(char[] ch,int i,int j){
char tmp=ch[i];
ch[i]=ch[j];
ch[j]=tmp;
}
}
总结
本题来源于面试经典教材《剑指offer》中 归属于全排序类型题目。
同许多在算法道路上不断前行的人一样,不断练习,修炼自己!
如有博客中存在的疑问或者建议,可以在下方留言一起交流,感谢各位!
最后,感谢AIAS!
觉得本博客有用的客官,可以给个赞鼓励下! 嘿嘿