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(numsindex);

tranceBack(nums,target-numsindex,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;
}
相关推荐
醉颜凉25 分钟前
区块链不可篡改机制全解析:从哈希锁链到51%攻击
算法·区块链·哈希算法
飞花漫卷,情随岁迁31 分钟前
命令进阶与 Playbook 快速入门
java·linux·运维·服务器·网络·数据库·智能路由器
hookserver34 分钟前
企业微信 iPad 协议全功能接入效果实测
java·http·微信·企业微信·ipad
IT枫斗者35 分钟前
缓存和数据库一致性:先更库还是先删缓存,延迟双删怎么落地
java·开发语言·数据库·人工智能·缓存·gateway
我是伪码农38 分钟前
12.5程序设计
数据结构·算法
播播资源44 分钟前
MiniMax-M4 API 选型指南:接入、思考参数与缓存避坑(含实测数据)
java·spring·缓存
Shaoshing1 小时前
LeetCode100 152.乘积最大子数组
数据结构·算法·leetcode
凡人叶枫1 小时前
数据结构分类与基本类型:线性、非线性、连续与分散
数据结构·c++
软件技术NINI1 小时前
基于 SpringBoot 的共享植物管理系统
java·spring boot·后端
吞下星星的少年·-·1 小时前
力扣 162. 寻找峰值(枚举,二分查找)
算法·leetcode·枚举·二分