//用的搜索算法 深度优先搜索 寻找xxx 仍然考你是否会写递归
class Solution{
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] nums){
//把所有的都找出来再去重,[1,1,1,1,1]的子集2^5时间复杂度极高
//return 一个result
ArrayList<ArrayList<Integer>> results=new ArrayList<>()
//异常判断
if(nums==null||nums.length==0){
return results;
}
Arrays.sort(nums);
ArrayList<Integer>subset=new ArrayList<>()
subsetsHelper(nums,0,subset,results)
//这个函数是把数组中0开始当日按subset开头的所有元素都放进去
return results;
}
//因为只被自己调了,没必要给外面知道
private void subsetsHelper(int[] nums,
int startIndex,
ArrayList<Integer> subset,
ArrayList<ArrayList<Integer>> results){
//deep copy subset&add to results
results.add(new ArrayList<Integer>(subset));
for(int i =startIndex;i<nums.length;i++){
if(i!=0&&nums[i]==nums[i-1]&&i>startIndex){
comtinue;
}
subset.add(nums[i]);
//挑出来[1,2]只能从3再开始 i+1
subsetsHelper(nums,i+1,subset,results)
subset.remove(subset.size()-1);
}
}
}
All recursive search, first add a number in, then move it away, is backtracking
search algorithm is actually a process of trying to backtrack similar enumeration, the main problem is to find a solution in the process of trying to search, find longer satisfied when solving when conditions on the "back" to return to try a different path. Backtracking is a search method selected from the preferred, optimal selection by the forward search conditions to achieve the goal. But when a step to explore, discover original choice is not superior or to meet its target, it is a step back to re-select, this dead end on the return walk technology for backtracking, and meet back at some point state conditions called "backtrack point." Many complex, large-scale problems can use backtracking, laudatory "universal problem-solving approach".
subset.add (the nums [I]);
subset.remove (subset.size () -. 1);
This part is a routine, remember