Combination

来源:互联网 发布:淘宝宝贝图片怎么上传 编辑:程序博客网 时间:2024/06/04 17:42

Combination

题目:

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],]

代码如下:

    void getSub(int n, int k, int start, vector<int>& solution, vector<vector<int> >& result) {        if (solution.size() == k) {            result.push_back(solution);            return;        }        for (int i = start; i <= n; i++) {            solution.push_back(i);            getSub(n, k, i + 1, solution, result);            solution.pop_back();        }    }

解题思路:

采用递归算法,用 solution 保存所需要的单个组合, result 保存所有产生的组合。

原创粉丝点击