LintCode 135-数字组合 回溯法
来源:互联网 发布:蜜蜂软件怎么注册 编辑:程序博客网 时间:2024/06/02 02:59
本人电子系,只为一学生。心喜计算机,小编以怡情。
给出一组候选数字(C)和目标数字(T),找到C中所有的组合,使找出的数字和为T。C中的数字可以无限制重复被选取。
例如,给出候选数组[2,3,6,7]和目标数字7,所求的解为:
[7],[2,2,3]
注意事项
所有的数字(包括目标数字)均为正整数。
元素组合(a1, a2, … , ak)必须是非降序(ie, a1 ≤ a2 ≤ … ≤ ak)。
解集不能包含重复的组合。
样例
给出候选数组[2,3,6,7]和目标数字7
返回 [[7],[2,2,3]]
这里用到了自己写的两个小函数,一个是getsum()求ArrayList和,
一个是判断是否是升序isup()
//主,主要是为给递归的副函数提供形参static public List<ArrayList<Integer>> combinationSum(int[] candidates, int target) { // write your code here ArrayList<Integer> temp=new ArrayList<>(); List<ArrayList<Integer>>ret=new ArrayList<>(); ret=subsum(temp,ret,candidates,target); return ret;}//副 static List<ArrayList<Integer>>subsum( ArrayList<Integer> temp,List<ArrayList<Integer>>ret ,int []candidates,int target) { if(isup(temp))//判断是够升序 if(getsum(temp)==target)//如果是目标函数 { boolean flag=false;//并且ret检验没有重复添加的 for(int i=0;i<ret.size();i++) if(ret.get(i).equals(temp)) flag=true; if(!flag) ret.add(new ArrayList<>(temp));//就ret添加 return ret; } else{//否则 for(int j=0;j<candidates.length;j++)//列举其他可能解 { temp.add(candidates[j]); if(isup(temp))//如果升序 if(getsum(temp)<=target)//并且目前求和不大于目标 subsum(temp, ret, candidates, target);//继续递归 temp.remove(temp.size()-1);//一定要将试探的解解除掉才行。 } } return ret; }//求和小函数static int getsum(ArrayList<Integer> temp){ if(temp.size()==0) return 0; int sum=0; for(int i:temp) sum+=i; return sum;}//判断升序小函数static boolean isup(ArrayList<Integer> temp){ for(int i=0;i<temp.size()-1;i++) if(temp.get(i)>temp.get(i+1)) return false; return true;}
0 0
- LintCode 135-数字组合 回溯法
- LintCode 152-组合 回溯法
- lintcode-数字组合-135
- [Lintcode] #135 数字组合
- LintCode-数字组合 II
- LintCode:数字组合
- LintCode:数字组合 II
- lintcode ----数字组合
- LintCode: 数字组合 II
- LintCode:数字组合
- 数字组合II-lintcode
- lintcode--数字组合
- lintcode -- 数字组合II
- 数字组合-LintCode
- lintcode--数字组合Ⅱ
- lintcode-数字组合II-153
- [Lintcode] #153 数字组合 II
- LINTCODE——数字组合,数字组合II
- Linux C 字符串操作
- 莫队算法及其应用
- 插入排序
- 使用cocos2dx制作 帧同步 游戏
- Android开发——JobScheduler机制以及Android电量优化
- LintCode 135-数字组合 回溯法
- 每天读一点好玩心理学--记忆
- IOC控制反转
- java中的匿名内部类
- 牢记ConnectionFactory(数据库连接),jdbcTemplate(CRUD)模板,学习更有效率
- HDU 2035 人见人爱A^B(同余基本性质)
- 数组sort方法的原理
- [LeetCode]260. Single Number III
- Linux下Java中文字体不显示(解决图像中文乱码问题)