剑指Offer27 字符串的排列

参考文章:
https://blog.csdn.net/snow_7/article/details/52459324
https://blog.csdn.net/zjxxyz123/article/details/79709240
题目:
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
采用递归的思想:

把需要全排列的字符串分为两部分看待:

(1)字符串的第一个字符;

(2)第一个字符后面的所有字符;

求所有可能出现在第一个位置的字符;将第一个字符和后面的字符一次交换;

固定第一个字符,对第一个字符后面的所有字符求全排列。第一个字符后面的所有字符又可以分为两部分;

import java.util.ArrayList;
import java.util.TreeSet;

public class Solution {
    public ArrayList<String> Permutation(String str) {
        ArrayList<String> result = new ArrayList<>();
        if(str.length()==0 || str == null) return result;
        TreeSet<String> temp = new TreeSet<>();
        char[] charStr = str.toCharArray();
        doPermutation(charStr,0,temp);
        result.addAll(temp);
        return result;
    }
    public void doPermutation(char[] charStr,int loc,TreeSet<String> temp){
        if(loc > charStr.length-1) return ;
        if(loc == charStr.length-1){
            temp.add(String.valueOf(charStr));
        }
        for(int i=loc; i<charStr.length; i++){
            swap(charStr,loc,i);
            doPermutation(charStr,loc+1,temp);
            swap(charStr,loc,i);
        }
    }
    public void swap(char[] str,int a, int b){
        char temp = str[a];
        str[a] = str[b];
        str[b] = temp;
    }

   public static void main(String[] args) {
       Solution solution = new Solution();
       System.out.println(solution.Permutation(new String("abc")));
   }

}

猜你喜欢

转载自blog.csdn.net/Wangfulin07/article/details/81389027