要特别注意在for循环里的递归,相当于每一次递归又包含了n次递归。因此递归return的位置,要注意别搞错。
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> listAll=new ArrayList<List<Integer>>();
List<Integer> list=new ArrayList<Integer>();
//排序
Arrays.sort(candidates);
find(listAll,list,candidates,target,0);
return listAll;
}
public void find(List<List<Integer>> listAll,List<Integer> tmp,int[] candidates, int target,int num){
//递归的终点
if(target==0){
listAll.add(tmp);
return;
}
if(target<candidates[0]) return;
for(int i=num;i<candidates.length&&candidates[i]<=target;i++){
//拷贝一份,不影响下次递归
List<Integer> list=new ArrayList<>(tmp);
list.add(candidates[i]);
//递归运算,将i传递至下一次运算是为了避免结果重复。
find(listAll,list,candidates,target-candidates[i],i);
}
}
}
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
//System.out.println(candidates);
backtrack(candidates, target, res, 0, new ArrayList<Integer>());
return res;
}
private void backtrack(int[] candidates, int target, List<List<Integer>> res, int i, ArrayList<Integer> tmp_list) {
if (target < 0) return;
if (target == 0) {
res.add(new ArrayList<>(tmp_list));
return;
}
for (int start = i; start < candidates.length; start++) {
if (target < 0) break;
//System.out.println(start);
tmp_list.add(candidates[start]);
//System.out.println(tmp_list);
backtrack(candidates, target - candidates[start], res, start, tmp_list);
tmp_list.remove(tmp_list.size() - 1);
}
}
}
No.46 全排列(待吃透)
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result=new ArrayList<>();
int[] visited=new int[nums.length];
backtrack(result,new ArrayList<>(),visited,nums);
return result;
}
private void backtrack(List<List<Integer>> result,List<Integer> temp,int[] visited,int[] nums){
if(temp.size()==nums.length){
result.add(new ArrayList<>(temp));
return;
}
for(int i=0;i<nums.length;i++){
if(visited[i]==1) continue;
visited[i]=1;
temp.add(nums[i]);
backtrack(result,temp,visited,nums);
visited[i]=0;
temp.remove(temp.size()-1);
}
}
}