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;
}
相关推荐
不知天地为何吴女士1 小时前
Day32| 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
算法
小坏坏的大世界1 小时前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
我命由我123452 小时前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list
励志要当大牛的小白菜3 小时前
ART配对软件使用
开发语言·c++·qt·算法
qq_513970443 小时前
力扣 hot100 Day56
算法·leetcode
武子康4 小时前
Java-80 深入浅出 RPC Dubbo 动态服务降级:从雪崩防护到配置中心秒级生效
java·分布式·后端·spring·微服务·rpc·dubbo
PAK向日葵4 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱装代码的小瓶子6 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
爱喝矿泉水的猛男6 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展
YuTaoShao7 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先