77. Combinations (JAVA)

博客围绕给定两个整数n和k,求1到n中所有可能的k个数组合展开,提到使用带回溯的递归方法实现,且指出带回溯无法用循环实现,还给出了转载来源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

 

带回溯的递归。(带回溯没法用循环实现)

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        result = new ArrayList<>();
        List<Integer> ans = new ArrayList<Integer>();
        dfs(ans,n,k,1);
        return result;
    }
    
    void dfs(List<Integer> ans, int n, int k, int depth){
        if(ans.size()==k) {
            List<Integer> new_ans = new ArrayList<Integer>(ans);
            result.add(new_ans);
            return;
        }
        if(depth>n){
            return;
        }
        
        ans.add(depth);
        dfs(ans,n,k,depth+1);
        ans.remove(ans.size()-1);
        dfs(ans,n,k,depth+1);
        
    }
    
    private List<List<Integer>> result;
}

 

转载于:https://www.cnblogs.com/qionglouyuyu/p/10929529.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值