【Lintcode】152. Combinations

题目地址:

https://www.lintcode.com/problem/combinations/description

给定正整数 n n n k k k,返回所有 ( 1 , 2 , 3 , . . . , n ) (1,2,3,...,n) (1,2,3,...,n)中取出 k k k个数的所有组合。

思路是DFS,从某个数字开始枚举,将其加入一个列表中,然后递归枚举下一个。每次发现列表中有 k k k个数后就说明产生了一种组合,则将其加入最终结果中。代码如下:

import java.util.ArrayList;
import java.util.List;

public class Solution {
    /**
     * @param n: Given the range of numbers
     * @param k: Given the numbers of combinations
     * @return: All the combinations of k numbers out of 1..n
     */
    public List<List<Integer>> combine(int n, int k) {
        // write your code here
        List<List<Integer>> res = new ArrayList<>();
        dfs(n, 1, k, new ArrayList<>(), res);
        return res;
    }
    
    private void dfs(int n, int pos, int k, List<Integer> cur, List<List<Integer>> res) {
    	// 如果cur里有了k个数了,就说明产生了一种组合,则将其加入res中
        if (cur.size() == k) {
            res.add(new ArrayList<>(cur));
            return;
        }
    	
    	// 开始从pos处开始枚举,
    	// 由于从i到n一共有n - i + 1个数,而cur中还需要加k - cur.size()个数,
    	// 只有当还剩下的数大于cur中还需要添加的数的个数的时候,才去枚举,否则就应该跳出循环
        for (int i = pos; k - cur.size() <= n - i + 1; i++) {
            cur.add(i);
            dfs(n, i + 1, k, cur, res);
            cur.remove(cur.size() - 1);
        }
    }
}

时间复杂度 O ( k ( n k ) ) O(k {n\choose k}) O(k(kn)),空间 O ( k ) O(k) O(k)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值