- import java.util.*;
- public class Solution {
- public ArrayList<String> Permutation(String str){
- ArrayList<String> ret = new ArrayList<>();
- if(str!=null || str.length()>0){
- helper(str.toCharArray(),0,ret);
- Collections.sort(ret);
- }
- return ret;
- }
- private void helper(char[] chars, int pos, ArrayList<String> ret){
- if(pos == chars.length-1) ret.add(String.valueOf(chars));
- Set<Character> charSet = new HashSet<>();
- for(int i=pos; i<chars.length; i++){
- if(!charSet.contains(chars[i])){
- charSet.add(chars[i]);
- swap(chars, i, pos);
- helper(chars, pos+1, ret);
- swap(chars, pos, i);
- }
- }
- }
- private void swap(char[] chars, int i, int j){
- char temp = chars[i];
- chars[i] = chars[j];
- chars[j] = temp;
- }
- }
来源: http://www.bubuko.com/infodetail-2971806.html