您的位置:首页 > Web前端

剑指offer第28题:字符串的排列

2016-07-31 23:53 246 查看
输入:abc

输出:abc acb bac bca cab cba

思路:

字符串由两部分组成,第一个字符和后面的部分

1。先求所有可能出现在第一个位置的字符,

2。固定第一个字符,求后面字符的排列,递归

public class Permutation {
//    剑指offer第28题,字符串的排列
public void permutation(char[] ch){
if(ch == null || ch.length == 0){
return;
}

permutationString(ch,0);
}

private void permutationString(char[] ch,int index) {
int end = ch.length - 1;
if(index == end){
System.out.println(new String(ch));
}else {
for(int i = index; i <= end; i ++){
char temp = ch[index];
ch[index] = ch[i];
ch[i] = temp;
permutationString(ch,index+1);
//恢复前面的变化
temp = ch[index];
ch[index] = ch[i];
ch[i] = temp;
}
}
}
public static void main(String[] args){
char[] example = {'a','b','c','d'};
new Permutation().permutation(example);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息