剑指offer之字符串全排列

递归思想,把每个位置和后面的字符交换,即形成一个子排列。

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

public class Solution {
  public ArrayList Permutation(String str){
    ArrayList result = new ArrayList<>();

    if(null == str || str.isEmpty()){
      return result;
    }

    HashSet set = new HashSet<>();
    fun(set,str.toCharArray(),0);
    result.addAll(set);
    Collections.sort(result);
    return result;
  }

  private void fun(HashSet set,char[] str,int k){
    if(k == str.length){
      set.add(new String(str));
      return;
    }
    for(int i = k;i< str.length;i++){
      swap(str,i,k);
      fun(set,str,k + 1);
      swap(str,i,k);
    }
  }
  private void swap(char[] str,int i ,int j){
    if(i != j ){
      char t = str[i];
      str[i] = str[j];
      str[j] = t;
    }
  }
  public static void main(String[] args){
    String str = "abc";
    Solution solution = new Solution();
    System.out.println(solution.Permutation(str));
  }
}

你可能感兴趣的:(剑指offer)