77. Combinations

77. Combinations

题目

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

解析

class Solution_77 {
public:

    void help(vector<vector<int>>& vecs, vector<int> &vec,int i,int k,int n )
    {
        if (k==0)
        {
            vecs.push_back(vec);
            return;
        }
        if (i>n)
        {
            return;
        }

        vec.push_back(i + 1);
        help(vecs, vec, i + 1, k-1, n);
        vec.pop_back();
        help(vecs, vec, i + 1, k, n);

        return;

    }

    vector<vector<int>> combine(int n, int k) {

        vector<vector<int>> vecs;
        vector<int> vec;

        help(vecs,vec,0,k,n);

        return vecs;  
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8693126.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞