【一次过】Lintcode 152. 组合

39 篇文章 1 订阅

组给出两个整数n和k,返回从1......n中选出的k个数的组合。

样例

例如 n = 4 且 k = 2

返回的解为:

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

注意事项

不需要在意组合的顺序,但是你应该确保组合中的数字是有序的


解题思路:

标准DFS解法

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, k, new ArrayList<Integer>(), res, 1);
        
        return res;
    }
    
    private void dfs(int n, int k, List<Integer> list, List<List<Integer>> res, int index){
        if(list.size() == k){
            res.add(new ArrayList<Integer>(list));
            return;
        }
        
        for(int i = index; i <= n; i++){
            list.add(i);
            dfs(n, k, list, res, i + 1);
            list.remove(list.size() - 1);
        }
    }
}

//剪枝优化:
        //到现在还有k - list.size()个空位,也就是[i...n]至少要有k-list.size()个空位
        //所以i最多为n - (k - list.size()) + 1

将dfs中的for循环改为:

for(int i = index; i <= n - (k - list.size()) + 1; i++)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值