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;
}
相关推荐
kong790692835 分钟前
Java-Intellij IDEA 自动导包设置
java·ide·intellij-idea
alphaTao40 分钟前
LeetCode 每日一题 2025/12/15-2025/12/21
算法·leetcode
写写闲篇儿3 小时前
下一个更大元素(一)
数据结构·算法
twj_one5 小时前
Arthas使用
java
MobotStone5 小时前
从金鱼记忆到过目不忘:Transformer 如何让AI真正理解一句话?
算法
lizz315 小时前
C++模板编程:从入门到精通
java·开发语言·c++
炽烈小老头6 小时前
【每天学习一点算法 2025/12/19】二叉树的层序遍历
数据结构·学习·算法
shoubepatien6 小时前
JAVA -- 05
java·开发语言
寰天柚子6 小时前
Java并发编程中的线程安全问题与解决方案全解析
java·开发语言·python
memgLIFE6 小时前
Springboot 分层结构
java·spring boot·spring