LintCode 135-数字组合 回溯法

本人电子系,只为一学生。心喜计算机,小编以怡情。


给出一组候选数字(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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值