本文持续更新回溯算法相关题目~~
题目1:
给你一个整数数组 nums
,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
class Solution {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
public List<List<Integer>> subsets(int[] nums) {
backTrace(new ArrayList<Integer>(), 0, nums);
return lists;
}
private void backTrace(List<Integer> list, int from, int[] nums){
lists.add(new ArrayList(list));
for(int i=from;i<nums.length;i++){
list.add(nums[i]);
backTrace(list, i+1, nums);
list.remove((Object)nums[i]);
}
}
}
题目2:
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
输入:candidates = [2,3,6,7], target = 7,
所求解集为:[[7],[2,2,3]]
class Solution {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
backTrace(new ArrayList<Integer>(), candidates, 0, target);
return lists;
}
private void backTrace(List<Integer> list, int[] candidates, int total, int target){
if(total>target){//上次加完后,已经大于target了
return;
}else if(total==target){
List<Integer> willBeAdd = new ArrayList(list);
Collections.sort(willBeAdd);
if(!lists.contains(willBeAdd))
lists.add(willBeAdd);
return;
}
for(int i=0;i<candidates.length;i++){
list.add(candidates[i]);
backTrace(list, candidates, total+candidates[i], target);
list.remove(list.size()-1);
}
}
}