利用回溯算法解决字符串的排列问题
字符串的排列
http://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7
import java.util.*; public class Solution { ArrayList<String> res = new ArrayList<>(); TreeSet<String> paths = new TreeSet<>(); StringBuilder path = new StringBuilder(); boolean [] visited; public ArrayList<String> Permutation(String str) { if(str == null || str.equals("")){ return res; } char[] strs = str.toCharArray(); Arrays.sort(strs); visited = new boolean[strs.length]; dfs(strs, 0); res.addAll(paths); return res; } //回溯框架 public void dfs(char[] strs, int len){ if(len == strs.length){ paths.add(path.toString()); return; } for(int i = 0; i < strs.length; i++){ if(!visited[i]){ visited[i] = true; path.append(strs[i]); dfs(strs, len+1); visited[i] = false; path.deleteCharAt(path.length()-1); } } } }
剑指Offer题解 文章被收录于专栏
为了之后反复练习方便查阅。