Skip to content

Commit b4869c5

Browse files
authored
Create Combinations.cpp
1 parent f04fa97 commit b4869c5

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Leet Code/Combinations.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/* Leet Code */
2+
/* Title - Combinations */
3+
/* Created By - Akash Modak */
4+
/* Date - 06/06/2023 */
5+
6+
// Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
7+
8+
// You may return the answer in any order.
9+
10+
11+
12+
// Example 1:
13+
14+
// Input: n = 4, k = 2
15+
// Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
16+
// Explanation: There are 4 choose 2 = 6 total combinations.
17+
// Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.
18+
// Example 2:
19+
20+
// Input: n = 1, k = 1
21+
// Output: [[1]]
22+
// Explanation: There is 1 choose 1 = 1 total combination.
23+
24+
class Solution {
25+
public:
26+
void backtrack(int i, int j, int k, int n, vector<int> &temp, vector<vector<int>> & res){
27+
if(i==k){
28+
res.push_back(temp);
29+
return;
30+
}
31+
for(int l=j;l<=n;l++){
32+
temp.push_back(l);
33+
j++;
34+
backtrack(i+1,j,k,n,temp,res);
35+
temp.pop_back();
36+
}
37+
38+
}
39+
vector<vector<int>> combine(int n, int k) {
40+
vector<int> temp;
41+
vector<vector<int>> res;
42+
backtrack(0,1,k,n,temp,res);
43+
return res;
44+
}
45+
};

0 commit comments

Comments
 (0)