剑指offer-字符串-字符串的排列组合

题目

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。


  • 排列:逐位确定,递归。TreeSet有序(字典序)不重特性

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

public class Permutation {

    private ArrayList<String> allStrings = new ArrayList<>();
    private TreeSet<String> strSet = new TreeSet<>();
    public ArrayList<String> permutation(String str) {
        if(str == null || str.length() == 0)
            return allStrings;

        permutation(str.toCharArray(), 0);
        allStrings.addAll(strSet);

        return allStrings;
    }

    public void permutation(char[] chars, int first){
        if(chars.length == 0 || chars == null)
            return;
        if(first == chars.length -1)
            strSet.add(String.valueOf(chars));
        else{
            for(int i = first; i<chars.length; i++){
                swap(chars, first, i);
                permutation(chars, first + 1);

                //why???
                swap(chars, first, i);
            }
        }
    }

    public void swap(char[] chars, int first, int index){
        char temp = chars[first];
        chars[first] = chars[index];
        chars[index] = temp;
    }
}

  • 组合:状态枚举
public class LetterCombine {
    private ArrayList<String> comb = new ArrayList<>();
    private TreeSet<String> set = new TreeSet<>();
    public void combine(String str){
        if(str == null || str.length() == 0)
            return;
        char[] chars = str.toCharArray();
        int n = chars.length;
        for(int i = 1; i<(1<<n); i++){
            String temp = "";
            for(int j = 0; j<n; j++){
                if((i & (1<<j)) != 0)
                    temp += String.valueOf(chars[j]);
            }
            set.add(temp);
        }
        comb.addAll(set);
    }

猜你喜欢

转载自blog.csdn.net/baidu_22153679/article/details/80615864