Combination Sum III

本文探讨了使用回溯算法解决组合问题的具体实现,并通过两个示例代码展示了如何求解组合总数,包括优化过程和复杂度分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

思路回溯算法

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> totalResult=new ArrayList<List<Integer>>();
        int record[]={0,0,0,0,0,0,0,0,0,0};

        process(k, n, record, 1, 0, totalResult);

        return totalResult;

    }



    public void process(int k,int n,int record[],int i,int currentsum,List<List<Integer>> totalResult)
    {
        if(i>9)
        {
            return;
        }
        k--;
        record[i]=1;
        if(currentsum+i==n&&k==0)
        {
            List<Integer> result=new ArrayList<Integer>();
            for(int j=0;j<10;j++)
            {
                if(record[j]==1)
                {
                    result.add(j);
                }
            }
            totalResult.add(result);
            record[i]=0;
            return;
        }


        currentsum+=i;
        if(currentsum<n&&k>0)
        {
            process(k, n, record, i+1, currentsum, totalResult);
        }
        record[i]=0;
        currentsum-=i;
        k++;
        process(k, n, record, i+1, currentsum, totalResult);
        return;
    }
}

别人的算法

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        recur(new ArrayList<Integer>(),res,n,1,k);
        return res;
    }
    public void recur(List<Integer> temp,List<List<Integer>> res, int tar,int k,int count){
        if(tar==0&&count==0){
            res.add(temp);
            return;
        }
        if(count==0||tar<=0)return;

        for(int i=k;i<=9;i++){
            temp.add(i);
            recur(new ArrayList<Integer>(temp),res,tar-i,i+1,count-1);
            temp.remove(temp.size()-1);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值