博客
关于我
LeetCode - 77. 组合——回溯 + 剪枝
阅读量:360 次
发布时间:2019-03-04

本文共 1049 字,大约阅读时间需要 3 分钟。

要解决的问题是生成1到n中所有可能的k个数的组合。这种问题可以通过递归和深度优先搜索(DFS)来实现,确保每个组合都是唯一的且不考虑顺序。

解决思路

  • 递归和DFS:使用递归函数,采用深度优先搜索的方式,逐步构建每个组合。
  • 路径跟踪:在递归过程中,使用一个队列或列表来跟踪当前构建的组合路径。
  • 回溯:在递归结束后,恢复路径,以便尝试下一个可能的元素。
  • 终止条件:当路径的长度等于k时,将当前路径添加到结果中。
  • 边界条件:处理k大于n或k小于等于0的情况,直接返回空结果。
  • 代码实现

    import java.util.ArrayList;import java.util.Deque;import java.util.List;import java.util.ArrayDeque;public class Solution {    public List
    > combine(int n, int k) { List
    > res = new ArrayList<>(); if (k <= 0 || k > n) { return res; } Deque
    path = new ArrayDeque<>(); dfs(n, k, 1, path, res); return res; } private void dfs(int n, int k, int begin, Deque
    path, List
    > res) { if (path.size() == k) { res.add(new ArrayList<>(path)); return; } for (int i = begin; i <= n; i++) { path.addLast(i); dfs(n, k, i + 1, path, res); path.removeLast(); } }}

    代码解释

    • combine方法:初始化结果集合,处理边界条件,调用递归函数。
    • dfs方法:递归函数,检查路径长度是否达到k,遍历所有可能元素,递归构建组合,回溯路径。

    通过这种方法,可以高效地生成所有k元素的组合,确保每个组合都是唯一且按升序排列。

    转载地址:http://uper.baihongyu.com/

    你可能感兴趣的文章
    POJ 2488:A Knight&#39;s Journey
    查看>>
    SpringBoot为什么易学难精?
    查看>>
    poj 2545 Hamming Problem
    查看>>
    poj 2723
    查看>>
    poj 2763 Housewife Wind
    查看>>
    Qt笔记——模型/视图MVD 文件目录浏览器软件
    查看>>
    POJ 2892 Tunnel Warfare(树状数组+二分)
    查看>>
    poj 2965 The Pilots Brothers' refrigerator-1
    查看>>
    poj 3026( Borg Maze BFS + Prim)
    查看>>
    POJ 3041 - 最大二分匹配
    查看>>
    POJ 3041 Asteroids(二分匹配模板题)
    查看>>
    Qt笔记——标准文件对话框QFileDialog
    查看>>
    poj 3083 Children of the Candy Corn
    查看>>
    POJ 3083 Children of the Candy Corn 解题报告
    查看>>
    POJ 3253 Fence Repair C++ STL multiset 可解 (同51nod 1117 聪明的木匠)
    查看>>
    Qt笔记——控件总结
    查看>>
    poj 3262 Protecting the Flowers 贪心
    查看>>
    poj 3264(简单线段树)
    查看>>
    Qt笔记——布局管理三件套分割窗口、停靠窗口和堆栈窗口
    查看>>
    poj 3277 线段树
    查看>>