注意:理解回溯算法尽量采用动态规划的思路。
第一种,例子{1,2,3} ,子集问题即为各位有无两种情况,那么就可以直接搜索下去。
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> ans = new ArrayList<Integer>();
backtrack(res,ans,0,nums);
return res;
}
private void backtrack(List<List<Integer>> res, List<Integer> ans, int i, int[] nums) {
// TODO Auto-generated method stub
if(is_a_solution(ans,i,nums)){
res.add(new ArrayList<Integer>(ans)); // process solution. add into the result list
}else{
//i++;
int[] c = new int[2];
//constract_candidates(ans,i,c,nums);
c[0]=0;c[1]=1;
for(int k=0;k<c.length;k++){
if(c[k]==1) ans.add(nums[i]);
backtrack(res,ans,i+1,nums);
if(c[k]==1) ans.remove(ans.size()-1);
}
}
}
private void constract_candidates(List<Integer> ans, int i, int[] c, int[] nums) {
// TODO Auto-generated method stub
c[0]=0;
c[1]=1;
}
private boolean is_a_solution(List<Integer> ans, int i, int[] nums) {
// TODO Auto-generated method stub
return i==nums.length; /*if i==n-1*/
}
}
第二种,{1,2,3} = {1} + 剩下的。这种结构采用的是下面的算法:
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
backtrack(list, new ArrayList<>(), nums, 0);
return list;
}
private void backtrack(List<List<Integer>> list , List<Integer> tempList, int [] nums, int start){
list.add(new ArrayList<>(tempList));
for(int i = start; i < nums.length; i++){
tempList.add(nums[i]);
backtrack(list, tempList, nums, i + 1);
tempList.remove(tempList.size() - 1);
}
}