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());
}
}
}