> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/77.combinations.md).

# 77.Combinations

**77.Combinations**

难度:Medium

> 给定两个整数 n 和 k，返回 1 ... n 中所有可能的 k 个数的组合。

示例:

```
输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
```

可以采用递归的方法，n个数里找k个数，可以分两类，第一类有n，第二类没有。\
第一类可以看做是n-1个数里找k-1个数。\
第二类可以看做是n-1个数里找k个数。\
以此方式进行递归。\
注意判断特殊情况。

```
class Solution {

public:
    vector<vector<int>> combine(int n, int k) {
       // cout<<n<<"  "<<k<<endl;
        if(n<k) 
        {
            vector<vector<int>>res;
            return res;
        }
        if(n==k) {
            vector<int >tmp;
            for(int i=1;i<=n;i++)
                        tmp.push_back(i);
            vector<vector<int>>res;
            res.push_back(tmp);
            return res;
        }
        if(k==1)
        {
            vector<vector<int>> res;
            for(int i=1;i<=n;i++)
            {
                vector<int>tmp(1,i);
                res.push_back(tmp);
            }
            return res;
        }

        vector<vector<int>> res1= combine(n-1, k);
        vector<vector<int>>res2= combine(n-1, k-1);
        for(auto v: res2)
        {
            v.push_back(n);
            res1.push_back(v);
        }


        return res1;
    }
};
```

> 执行用时 :164 ms, 在所有 C++ 提交中击败了46.10%的用户\
> 内存消耗 :54.7 MB, 在所有 C++ 提交中击败了22.81%的用户


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://dfine.gitbook.io/leetcode/77.combinations.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
