77. 组合

作者: 红树_ | 来源:发表于2023-06-16 21:42 被阅读0次

参考77. 组合 - 力扣(Leetcode)

题目

给定两个整数 nk,返回范围 [1, n] 中所有可能的 k 个数的组合。

你可以按 任何顺序 返回答案。

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

解题思路

  • 位集合:数据范围较小可使用位集合进行选或不选的递归。
  • 回溯:使用队列进行选的回溯或不选的递归。

位集合

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> ans = new ArrayList<>();
        dfs(ans,n,k,0,0,0);
        return ans;
    }
    void dfs(List<List<Integer>> ans,int n,int k, int i,int hash,int count){
        if(count == k) {
            List<Integer> list = new ArrayList<>();
            int num = 1;
            while(hash != 0) {
                if((hash & 1) == 1) list.add(num);
                hash >>= 1;
                num ++;
            }
            ans.add(list);
            return;
        }
        //选
        dfs(ans,n,k,i+1,hash|(1<<i),count+1);
        //不选
        if(count + n-i > k) dfs(ans,n,k,i+1,hash,count);
    }
}

回溯

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> ans = new ArrayList<>();
        dfs(ans,n,k,1,new ArrayList<Integer>());
        return ans;
    }
    void dfs(List<List<Integer>> ans,int n,int k, int i,List<Integer> res){
        if(res.size() == k) {
            ans.add(new ArrayList<>(res));
            return;
        }
        //选
        res.add(i);
        dfs(ans,n,k,i+1,res);
        res.remove(res.size()-1);
        //不选
        if(res.size() + n-i >= k) dfs(ans,n,k,i+1,res);
    }
}

2023.06.17

相关文章

  • 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/wgzrydtx.html