组合总数(力扣)

// 剪枝优化
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates); // 先进行排序
        backtracking(res, new ArrayList<>(), candidates, target, 0, 0);
        return res;
    }

    public void backtracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int idx) {
        // 找到了数字和为 target 的组合
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = idx; i < candidates.length; i++) {
            // 如果 sum + candidates[i] > target 就终止遍历
            if (sum + candidates[i] > target) break;
            path.add(candidates[i]);
            backtracking(res, path, candidates, target, sum + candidates[i], i);
            path.remove(path.size() - 1); // 回溯,移除路径 path 最后一个元素
        }
    }
}

// 剪枝优化
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates); // 先进行排序
        backtracking(res, new ArrayList<>(), candidates, target, 0, 0);
        return res;
    }

    public void backtracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int idx) {
        // 找到了数字和为 target 的组合
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = idx; i < candidates.length; i++) {
            // 如果 sum + candidates[i] > target 就终止遍历
            if (sum + candidates[i] > target) break;
            path.add(candidates[i]);
            backtracking(res, path, candidates, target, sum + candidates[i], i);
        }
    }
}

  path.remove(path.size() - 1); // 回溯,移除路径 path 最后一个元素

这段代码说明list集合的删除方法,比较笨重。

 Deque<Integer> path = new ArrayDeque<>();

双端队列!!!

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
力扣是一个在线的编程题库,在其中有各种算法和数据结构的题目,供程序员进行练习。力扣题库支持多种编程语言,包括Python。 力扣Python格式是指在力扣平台上使用Python语言解答问题时需要注意的一些细节和规范。以下是一些力扣Python格式的要点: 1. 导入模块:根据题目需要,导入相应的Python模块。常见的模块如:math、collections等。 2. 主函数:在解题时,将代码写在一个主函数中。通常命名为def main()。 3. 输入输出:遵循力扣的输入输出格式。使用input函数获取输入数据,使用print函数输出结果。 4. 命名规范:遵循Python的命名规范。变量和函数名采用小写字母与下划线的组合,以便于代码的可读性。 5. 注释:在关键代码处添加注释,描述代码功能和思路。这不仅方便自己理解和维护代码,也方便他人阅读。 6. 缩进:使用统一的缩进风格,通常为4个空格或者1个制表符。 7. 算法实现:根据题目要求,选择合适的算法进行实现。可以使用循环、条件判断、递归等常见的编程结构。 8. 异常处理:对于可能出现异常的地方,使用try-except语句进行异常处理。 9. 提交代码:在完成代码编写后,将代码复制到力扣平台的代码编辑器中,然后点击提交按钮进行代码评测。 总之,力扣Python格式主要是指在力扣平台上使用Python语言解题时需要遵守的编码规范和格式要求。遵循这些规范可以提高代码的可读性和可维护性,从而更好地解决问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值