Lintcode 152 · Combinations (组合好题)

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();
        }
    }
};

你可能感兴趣的:(算法,数据结构)