77.组合

作者: 皮蛋豆腐酱油 | 来源:发表于2019-06-20 12:26 被阅读0次

给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

//回溯
class Solution {
  List<List<Integer>> output = new LinkedList();
  int n;
  int k;

  public void backtrack(int first, LinkedList<Integer> curr) {
    // if the combination is done
    if (curr.size() == k)
      output.add(new LinkedList(curr));

    for (int i = first; i < n + 1; ++i) {
      // add i into the current combination
      curr.add(i);
      // use next integers to complete the combination
      backtrack(i + 1, curr);
      // backtrack
      curr.removeLast();
    }
  }

  public List<List<Integer>> combine(int n, int k) {
    this.n = n;
    this.k = k;
    backtrack(1, new LinkedList<Integer>());
    return output;
  }

}

相关文章

  • 77.组合

    题目给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。 示例:输入: n = 4, k...

  • 77.组合

    给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。示例:输入: n = 4, k = ...

  • 77.组合

    原题 https://leetcode-cn.com/problems/combinations/ 解题思路 典型...

  • 77. 组合

    https://leetcode-cn.com/problems/combinations/

  • BackTracing——77. 组合

    首先这道题给了两个数字,一个是n——从1到n遍历,另一个是k——组合中的总个数。所以在遍历的时候我们可以先做一个限...

  • 77. Combinations/组合

    ShareGiven two integers n and k, return all possible comb...

  • 77. Combinations 组合

    题目 给定两个整数 n 和 k,在 [1,n] 之间返回 k 个数的组合。 由这个例子可知,其实就是求 Cnk 的...

  • 77. 组合/207. 课程表

    77. 组合 相关标签:回溯算法 207. 课程表 相关标签: DFS BFS 图 拓扑排序

  • 搜索(二)回溯

    一、题目总结 基础问题 46.全排列 77.组合 78.子集 39.组合求和 47.全排列 II(重复元素) 90...

  • LeetCode 力扣 77. 组合

    题目描述(中等难度) 给定 n ,k ,表示从 { 1, 2, 3 ... n } 中选 k 个数,输出所有可能,...

网友评论

      本文标题:77.组合

      本文链接:https://www.haomeiwen.com/subject/eaudqctx.html