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;
}
相关推荐
Funny_AI_LAB6 分钟前
MetaAI最新开源Llama3.2亮点及使用指南
算法·计算机视觉·语言模型·llama·facebook
Cikiss8 分钟前
微服务实战——SpringCache 整合 Redis
java·redis·后端·微服务
wxin_VXbishe8 分钟前
springboot合肥师范学院实习实训管理系统-计算机毕业设计源码31290
java·spring boot·python·spring·servlet·django·php
Cikiss9 分钟前
微服务实战——平台属性
java·数据库·后端·微服务
NuyoahC13 分钟前
算法笔记(十一)——优先级队列(堆)
c++·笔记·算法·优先级队列
jk_10115 分钟前
MATLAB中decomposition函数用法
开发语言·算法·matlab
无敌の星仔18 分钟前
一个月学会Java 第2天 认识类与对象
java·开发语言
OEC小胖胖23 分钟前
Spring Boot + MyBatis 项目中常用注解详解(万字长篇解读)
java·spring boot·后端·spring·mybatis·web
2401_857617621 小时前
SpringBoot校园资料平台:开发与部署指南
java·spring boot·后端
quokka561 小时前
Springboot 整合 logback 日志框架
java·spring boot·logback