Lintcode 152 · Combinations (组合好题)

本文介绍了一种解决给定整数n和k,找出1到n中所有k个数递增组合的算法,通过递归函数`helper`实现,适用于面试中组合问题的考察,如N皇后问题、表达式加法等

152 · Combinations
Algorithms
Medium

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

You can return all combinations in any order, but numbers in a combination should be in ascending order.

Example
Example 1:

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

Input: n = 4, k = 1
Output: [[1],[2],[3],[4]]
Related Knowledge
学习《算法求职课——百题精讲》课程中的14.5组合-视频讲解相关内容 ,了解更多相关知识!
Tags
Related Problems

34
N-Queens II
Medium

33
N-Queens
Medium

653
Expression Add Operators
Hard

740
Coin Change 2
Medium

739
24 Game
Hard

解法1:

class Solution {
public:
    /**
     * @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
     *          we will sort your return value in output
     */
    vector<vector<int>> combine(int n, int k) {
        vector<int> sol;
        vector<vector<int>> sols;
        helper(n, k, 1, sols, sol);
        return sols;
    }
private:
    void helper(int n, int k, int index, vector<vector<int>> &sols, vector<int> &sol) {
        if (sol.size() == k) {  //关键是这一行
            sols.push_back(sol);
            return;
        }
        for (int i = index; i <= n; i++) {
            sol.push_back(i);
            helper(n, k, i + 1, sols, sol);
            sol.pop_back();
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值