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

来源:互联网 发布:淘宝允许好评返现吗 编辑:程序博客网 时间:2024/06/01 04:00

输入: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);    }}
0 0
原创粉丝点击