标签:style blog color java os io for ar div
还是permutation的算法,字符串也没什么太大的区别。 先排序,然后注意如何去重。
import java.util.ArrayList; import java.util.Arrays; public class Solution { public static ArrayList<String> getPerms(String str) { ArrayList<String> res = new ArrayList<String>(); if (str == null || str.length() == 0) return res; StringBuilder sb = new StringBuilder(); char[] strs = str.toCharArray(); Arrays.sort(strs); perm(res, sb, new String(strs)); return res; } private static void perm(ArrayList<String> res, StringBuilder sb, String str) { if (sb.length() == str.length()) { res.add(sb.toString()); return; } for (int i = 0; i < str.length(); i++) { // remove the duplicates if (i == 0 || str.charAt(i) != str.charAt(i - 1)) { int all = 0; int cur = 0; for (int j = 0; j < str.length(); j++) { if (str.charAt(j) == str.charAt(i)) { all++; } } // be careful: sb.length() for (int j = 0; j < sb.length(); j++) { if (sb.charAt(j) == str.charAt(i)) { cur++; } } if (cur < all) { sb.append(str.charAt(i)); perm(res, sb, str); sb.deleteCharAt(sb.length() - 1); } } } } public static void main(String[] args) { int[] a = { 0, 2, 4, 5 }; System.out.println(getPerms("aba")); } }
标签:style blog color java os io for ar div
原文地址:http://www.cnblogs.com/jdflyfly/p/3931834.html