字符串的排列
字符串的排列
http://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7
递归求解
import java.util.*; public class Solution { ArrayList<String> res = new ArrayList<String>(); public ArrayList<String> Permutation(String str) { if (str == null || str.length() == 0) { return res; } char[] c = str.toCharArray(); find(c, 0); // 字典序 Collections.sort(res); return res; } public void find(char[] c, int index) { if (index >= c.length) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < c.length; i++) { sb.append(c[i]); } String t = sb.toString(); // 去重 if (!res.contains(t)) { res.add(t); } } for (int i = index; i < c.length; i++) { swap(c, i, index); find(c, index + 1); swap(c, i, index); } } public void swap(char[] c, int i, int j) { char t = c[i]; c[i] = c[j]; c[j] = t; } }