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;
}
相关推荐
香吧香9 分钟前
java服务异常日志只打印异常类型,没有堆栈定位分析
java·jvm·异常
qq_25183645744 分钟前
AI 疾病自查功能SpringbootAI项目实战 · 技术实现文档
java·ai·ai编程
mmmmath_31 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z1 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
逆境不可逃1 小时前
Pi Agent 学习笔记:对话太长以后,如何压缩上下文
java
MetaLite1 小时前
JDK 8~26 核心特性一览:从 Stream 到 Scoped Values
java
wno7042 小时前
Spring Boot WebFlux增删改查
java·spring boot·后端
君顾12 小时前
上海24小时自助健身房系统开发实战指南:从架构设计到落地部署
java·开发语言·健身房
醇氧2 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法