字符串的排列
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; } }
posted on 2019-03-01 09:36 www_practice 阅读(125) 评论(0) 编辑 收藏 举报