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;
}
相关推荐
VkN2X2X4b21 小时前
算法性能的渐近与非渐近行为对比的技术9
算法
好家伙VCC21 小时前
**神经编码新视角:用Python实现生物启发的神经信号压缩与解码算法**在人工智能飞速发展的今天
java·人工智能·python·算法
一灯架构1 天前
90%的人答错!一文带你彻底搞懂ArrayList
java·后端
W23035765731 天前
经典算法:最长上升子序列(LIS)深度解析 C++ 实现
开发语言·c++·算法
Y4090011 天前
【多线程】线程安全(1)
java·开发语言·jvm
2401_892070981 天前
链栈(链式栈) 超详细实现(C 语言 + 逐行精讲)
c语言·数据结构·链栈
布局呆星1 天前
SpringBoot 基础入门
java·spring boot·spring
minji...1 天前
Linux 线程同步与互斥(三) 生产者消费者模型,基于阻塞队列的生产者消费者模型的代码实现
linux·运维·服务器·开发语言·网络·c++·算法
风吹迎面入袖凉1 天前
【Redis】Redisson的可重入锁原理
java·redis
w6100104661 天前
cka-2026-ConfigMap
java·linux·cka·configmap