77. Combinations (M)

本文探讨了从n个数中选择k个数的所有可能组合。通过使用回溯法,有效地解决了组合问题,并提供了详细的代码实现。文章重点介绍了算法的思路和剪枝技巧。

Combinations (M)

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

题意

从n个数中选取k个组成集合,输出所有这样的集合。

思路

回溯法,注意剪枝。


代码实现

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> ans = new ArrayList<>();
        combine(n, k, 1, new ArrayList<>(), ans);
        return ans;
    }

    private void combine(int n, int k, int cur, List<Integer> list, List<List<Integer>> ans) {
        if (list.size() == k) {
            ans.add(new ArrayList<>(list));
            return;
        }

        // 只有当剩余元素数加上已加入列表元素数大于等于k时,才需要继续递归
        for (int i = cur; n - i + 1 >= k - list.size(); i++) {
            list.add(i);
            combine(n, k, i + 1, list, ans);
            list.remove(list.size() - 1);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值