LeetCode-Combinations

来源:互联网 发布:sql美化工具 编辑:程序博客网 时间:2024/06/05 20:26

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

Code:

<span style="font-size:14px;">class Solution {public:    void helper(int begin, int end, int k, vector<vector<int> > &results, vector<int> &result) {        if (k == 0)  {            results.push_back(result);                return;        }        if (end-begin+1 == k) {            vector<int> copy = result;            for (int i = begin; i <= end; i++)                result.push_back(i);            results.push_back(result);            result = copy;            return;        }        for (int i = begin; i <= end-k+1; i++) {            result.push_back(i);            helper(i+1, end, k-1, results, result);            result.pop_back();        }    }        vector<vector<int> > combine(int n, int k) {        vector<vector<int> > results;        vector<int> result;        helper(1, n, k, results, result);        return results;    }};</span>



0 0
原创粉丝点击