算法定义:
回溯算法(backtracking)是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。回溯算法的基本思想是:暴力算法的改进,在通过遍历所有路径基础上,通过回溯(往回找)筛除不可能的路径,提高效率。
算法步骤:
1、确定一个解空间,包含问题的解。
2、利用适于搜索的方法组织解空间。
3、利用深度优先法搜索解空间。
4、利用剪枝(约束函数、限界函数)避免移动到不可能产生解的子空间。
算法示例:
1、给定一个没有重复数字的序列,返回其所有可能的全排列。
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
public List<List<Integer>> permute(int[] nums) {
List<Integer> temp = new ArrayList<Integer>();
List<List<Integer>> list = new ArrayList<List<Integer>>();
backTrace(list,temp,nums);
return list;
}
private void backTrace(List<List<Integer>> list,List<Integer> temp,int[] nums)
{
if(temp.size() == nums.length)
{
list.add(new ArrayList<>(temp));
}
else
{
for(int i=0;i<nums.length;i++)
{
if(temp.contains(nums[i]))
{
continue;
}
else
{
temp.add(nums[i]);
backTrace(list,temp,nums);
temp.remove(temp.size()-1);
}
}
}
}
2、给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
示例:
输入: S = “a1b2”
输出: [“a1b2”, “a1B2”, “A1b2”, “A1B2”]
输入: S = “3z4”
输出: [“3z4”, “3Z4”]
输入: S = “12345”
输出: [“12345”]
注意:
S 的长度不超过12。
S 仅由数字和字母组成。
public List<String> letterCasePermutation(String S) {
String temp = "";
S = S.toLowerCase();
List<String> list = new ArrayList<String>();
backTrack(list,S,temp);
return list;
}
private void backTrack(List<String>list,String S,String temp)
{
if(temp.length() == S.length())
{
list.add(temp);
}
else
{
if(temp.length() < S.length())
{
if(Character.isDigit(S.charAt(temp.length())))
{
temp += S.charAt(temp.length());
backTrack(list,S,temp);
temp = temp.substring(0,temp.length()-1);
}
else
{
temp += Character.toLowerCase(S.charAt(temp.length()));
backTrack(list,S,temp);
temp = temp.substring(0,temp.length()-1);
temp += Character.toUpperCase(S.charAt(temp.length()));
backTrack(list,S,temp);
temp = temp.substring(0,temp.length()-1);
}
}
}
}