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

# 77. Combinations

## 1.問題

* 給予n與k, 回傳長度為k的組合

![](/files/-LNASe19Mjt-pwrsgF_G)

## 2.想法

* 提問:
* function header, parameter
* test input
* 說明想法&#x20;
  * DFS, 當累積數量為特定大小時返回, 但要注意要設定start
* 測試計算複雜度

## 3.程式碼

```
class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> res;
        vector<int> record;
        combination(res, record, n, k, 0); 
        return res;
    }
private:
    void combination(vector<vector<int>>& res, vector<int>& record, int n, int k, int start)  {
        if (record.size() == k) {
            res.push_back(record);
            return;
        }
        
        for (int i = start; i < n ; i++) {
            record.push_back(i + 1);
            combination(res, record, n, k, i + 1); 
            record.pop_back();
        }
    }
};
```


---

# 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:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/77.-combinations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
