暴力递归-打印字符串全部序列
题目:打印一个字符串的全部序列,不能出现重复的排序
package Algorithms.ViolenceRecursive; import java.util.ArrayList; public class PrintAllPermutations { public static ArrayList<String> Permutation(String str) { ArrayList<String> res = new ArrayList<>(); if (str == null || str.length() == 0) { return res; } char[] chs = str.toCharArray(); process(chs, 0, res); res.sort(null); return res; } //str[i...]范围上,所有的字符都可以在i位置上,后续都去尝试 //str[0...i-1]范围上,是之前做的选择 //请把所有的字符串形成的全排列,加入到res里去 public static void process(char[] chs, int i, ArrayList<String> res) { if (i == chs.length) { res.add(String.valueOf(chs)); } boolean[] visit = new boolean[26]; //存放试过的字符 for (int j = i; j < chs.length; j++) { if (!visit[chs[j] - 'a']) { //若字符没有试过 visit[chs[j] - 'a'] = true; //存放到visit中 swap(chs, i, j); process(chs, i + 1, res); swap(chs, i, j); } } } public static void swap(char[] chs, int i, int j) { char tmp = chs[i]; chs[i] = chs[j]; chs[j] = tmp; } public static void main(String[] args) { String str = "abc"; ArrayList<String> p = Permutation(str); for (String s:p){ System.out.println(s.toString()); } } } /** * abc * acb * bac * bca * cab * cba */