LeetCode–组合

博客说明

文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!

介绍

77. 组合

题目

给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。

示例:
输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

代码

class Solution {
    List<Integer> temp = new ArrayList<Integer>();
    List<List<Integer>> ans = new ArrayList<List<Integer>>();

    public List<List<Integer>> combine(int n, int k) {
        dfs(1, n, k);
        return ans;
    }

    public void dfs(int cur, int n, int k) {
        // 剪枝:temp 长度加上区间 [cur, n] 的长度小于 k,不可能构造出长度为 k 的 temp
        if (temp.size() + (n - cur + 1) < k) {
            return;
        }
        // 记录合法的答案
        if (temp.size() == k) {
            ans.add(new ArrayList<Integer>(temp));
            return;
        }
        // 考虑选择当前位置
        temp.add(cur);
        dfs(cur + 1, n, k);
        temp.remove(temp.size() - 1);
        // 考虑不选择当前位置
        dfs(cur + 1, n, k);
    }

}

感谢

Leetcode

以及勤劳的自己,个人博客GitHub

LeetCode–组合

相关文章:

  • 2021-10-24
  • 2022-02-08
  • 2022-02-16
  • 2021-12-28
  • 2022-01-27
  • 2022-12-23
  • 2022-12-23
  • 2021-11-18
猜你喜欢
  • 2021-07-11
  • 2021-04-19
  • 2021-09-16
  • 2021-12-09
  • 2021-07-14
  • 2022-12-23
  • 2022-01-04
相关资源
相似解决方案