***剑指offer——字符串的排列(不会)

字符串的排列

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

解:就是将字符串abc当前位置的字符和下一个字符进行交换,递归

import java.util.ArrayList;
import java.util.TreeSet;
public class Solution {
    public ArrayList<String> Permutation(String str) {
       ArrayList<String> arrayList = new ArrayList<>();
        if(str == null || str.length() == 0) return arrayList;
        char[] ch = str.toCharArray();
        TreeSet<String> res = new TreeSet<>();
        getsubStr(res, ch, 0);
        arrayList.addAll(res);
        return arrayList;
    }
    public void getsubStr(TreeSet<String> res, char[] ch, int index){
        if(index == ch.length - 1){
             res.add(String.valueOf(ch));
        } else{
            for(int i = index; i < ch.length; i++){
                swap(ch, index, i);
                getsubStr(res, ch, index + 1);
                swap(ch, index, i);
            }
        }
    }
    public void swap(char[] ch, int i, int j){
        char temp = ch[i];
        ch[i] = ch[j];
        ch[j] = temp;
    }
}

  

原文地址:https://www.cnblogs.com/SkyeAngel/p/8674999.html