Problem
Give a string, like “abc”, return all the possible combinations (all the chars are different)
example:
input: “abc”
output: [abc, acb, bac, bca, cab, cba]
Analysis
obviously, this problem can be solved by dfs. We should know that all the dfs problem can be shown as a tree form. So once we transfer the problem into a tree, the problem is solved.
" "
/ | \
a b c
| \ | \ | \
ab ac ba bc ca cb
| | | | | |
abc acb bac bca cab cba
Coding
// An highlighted block
class Solution1 {
public static List<String> mutation(String str){
List<String> res = new LinkedList<String>();
String temp = "";
dfs(str, res, temp, str.length());
return res;
}
public static void dfs(String str, List<String> res, String temp, int len ) {
// base case
if (temp.length() == len) {
res.add(temp);
return;
}
// recursive rule
for (int i=0; i<str.length(); i++) {
if (temp.indexOf(str.charAt(i)) < 0) {
dfs(str, res, temp + str.charAt(i), str.length());
}
}
}

本文深入探讨了如何使用深度优先搜索(DFS)算法解决字符串全排列问题,通过树形结构展示递归过程,详细解释了从输入字符串到输出所有可能组合的实现细节。
1377

被折叠的 条评论
为什么被折叠?



