58 回溯算法求组合问题

问题描述:给定一个无重复元素的数组nums和一个目标数,找出nums中所有可以使数字和为target的组合;

回溯分析:没个数都有选与不选两种情况,所以回溯深度为nums.length,一旦当前target==0,则加入组合中,到达最后都不能使得target==0,则返回。

public void tranceBack(int []nums,int target,Link<Integer>templist,int index,List<List<Integer>>res)

{

if(target==0){res.add(new Link<Integer>(templist));return;}

if(index==nums.length){return;}

templist.add(nums[index]);

tranceBack(nums,target-nums[index],templist,index+1,res);

templist.remove(templist.size()-1);

tranceBack(nums,target,templist,index+1,res);

}

public List<List<Integer>> TranceBack(int []nums,int target)

{

List<List<Integer>>res=new List<List<Integer>>();

tranceback(nums,target,new Link<Integer>(),0,res);

return res;

}

//可以看成是求组合问题,需要组合的数字从小到大排列,从而考虑重复问题。

java 复制代码
public void tranceBack(int []nums,int index,int target,List<Integer>templist,List<List<Integer>>res)
{
if(target==0){res.add(templist);return;}
for(int i=index;i<nums.length;i++)
{
templist.add(nums[i]);
tranceBack(nums,i+1;target+nums[i],templist,res);
templist.remove(templist.size()-1);
}
}
public List<List<Integer>> TranceBack(int []nums,int target)
{
List<List<Integer>>res=new List<List<Integer>>();
tranceBack(nums,0,target,new List<Integer>(),res);
​​​​​​​return res;
}
相关推荐
包饭厅咸鱼12 分钟前
PaddleOCR----制作数据集,模型训练,验证 QT部署(未完成)
算法
百锦再25 分钟前
第12章 测试编写
android·java·开发语言·python·rust·go·erlang
无敌最俊朗@26 分钟前
C++ 并发与同步速查笔记(整理版)
开发语言·c++·算法
王哈哈^_^27 分钟前
【完整源码+数据集】课堂行为数据集,yolo课堂行为检测数据集 2090 张,学生课堂行为识别数据集,目标检测课堂行为识别系统实战教程
人工智能·算法·yolo·目标检测·计算机视觉·视觉检测·毕业设计
C2H5OH66632 分钟前
Netty详解-02
java·websocket·网络协议·tcp/ip·tomcat·netty·nio
夏鹏今天学习了吗42 分钟前
【LeetCode热题100(66/100)】寻找两个正序数组的中位数
算法·leetcode·职场和发展
墨染点香1 小时前
LeetCode 刷题【151. 反转字符串中的单词】
算法·leetcode·职场和发展
小张成长计划..1 小时前
【C++】List容器的理解和使用(超详细)
数据结构·list
跟着珅聪学java1 小时前
HttpServletRequest中的 Attribute(属性)生命周期和作用域是 Java Web 开发中的重要概念
java