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
原创粉丝点击