LeetCode每日一题 216. Combination Sum III

216. Combination Sum III

Tag BackTracking

Difficulty Medium

Link https://leetcode-cn.com/problems/combination-sum-iii/

思路

这道题和前面的两道组合数之和类似,只不过增加了对每条路径的元素数量的限制

candidates限定为[1,2,3,4,5,6,7,8,9]

仿照前面的模板,可以很轻易的写出如下代码

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        if (k <= 0 || n <= 0 || n > 55) {
            return res;
        }
        Deque<Integer> path = new ArrayDeque<>();
        int[] candidates = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        dfs(candidates, k, n, 0, path, res);
        return res;
    }
    
    public void dfs(int[] candidates, int k, int n, int begin, Deque<Integer> path, List<List<Integer>> res) {
      	// 基准条件
        if (k == 0 && n == 0) {
            res.add(new ArrayList<>(path));
            return;
        }
        if (k == 0 || n == 0) {
            return;
        }
        
        for (int i = begin; i < candidates.length; i++) {
            path.add(candidates[i]);
            dfs(candidates, k - 1, n - candidates[i], i + 1, path, res);
            path.removeLast();
        }
    }
}

当然,还可以通过剪枝对其进行优化,我们通过画图可以更加直观的看出来。

假设k=3,n=7

可以看到,在得到[1,2,4]这个正确组合后,程序还去判断了后续的[1,2,5],[1,2,6]等,这就造成了浪费。使用如下注释的地方的剪枝,可以超过100%的用户。

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        if (k <= 0 || n <= 0 || n > 55) {
            return res;
        }
        Deque<Integer> path = new ArrayDeque<>();
        int[] candidates = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        dfs(candidates, k, n, 0, path, res);
        return res;
    }
    
    public void dfs(int[] candidates, int k, int n, int begin, Deque<Integer> path, List<List<Integer>> res) {
        if (k == 0 && n == 0) {
            res.add(new ArrayList<>(path));
            return;
        }
        
        for (int i = begin; i < candidates.length; i++) {
            // 如果路径和还未达到n,则去后面寻找更大的数
            if (k == 1 && n - candidates[i] > 0) {
                continue;
            }
            // 大剪枝:如果路径和已经超过k,那么直接退出这条路径
            if (k == 1 && n - candidates[i] < 0) {
                break;
            }
            path.add(candidates[i]);
            dfs(candidates, k - 1, n - candidates[i], i + 1, path, res);
            path.removeLast();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值