Share 77. combinations leetcode c++,

phamangryphon

New member
#77.Kết hợp LeetCode C ++, #LeetCode, #C ++, #Combinations
## 77. Kết hợp LeetCode C ++

Cho hai số nguyên n và k, trả lại tất cả các kết hợp có thể của K số trong 1 ... n.

**Ví dụ:**

`` `
Đầu vào: n = 4, k = 2
Đầu ra:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4]
]
`` `

**Giải pháp:**

`` `C ++
Giải pháp lớp {
công cộng:
Vector <Vector <int >> Kết hợp (int n, int k) {
Vector <Vector <int >> res;
Vector <Int> đường dẫn;
backtrack (n, k, 1, đường dẫn, res);
trả lại res;
}

void Backtrack (int n, int k, int start, vector <int> & path, vector <vector <int >> & res) {
if (k == 0) {
res.push_back (đường dẫn);
trở lại;
}
for (int i = start; i <= n; i ++) {
path.push_back (i);
backtrack (n, k - 1, i + 1, đường dẫn, res);
path.pop_back ();
}
}
};
`` `

## 5 hashtags

* #LeetCode
* #C ++
* #Combinations
* #backtracking
* #lập trình năng động
=======================================
#77. Combinations Leetcode C++, #LeetCode, #C++, #Combinations
## 77. Combinations Leetcode C++

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

**Example:**

```
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4]
]
```

**Solution:**

```c++
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> path;
backtrack(n, k, 1, path, res);
return res;
}

void backtrack(int n, int k, int start, vector<int>& path, vector<vector<int>>& res) {
if (k == 0) {
res.push_back(path);
return;
}
for (int i = start; i <= n; i++) {
path.push_back(i);
backtrack(n, k - 1, i + 1, path, res);
path.pop_back();
}
}
};
```

## 5 Hashtags

* #LeetCode
* #C++
* #Combinations
* #backtracking
* #Dynamic programming
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top