https://github.com/emahtab/combinations
Combinations
https://github.com/emahtab/combinations
combinations leetcode problem-solving
Last synced: 7 months ago
JSON representation
Combinations
- Host: GitHub
- URL: https://github.com/emahtab/combinations
- Owner: eMahtab
- Created: 2020-06-21T11:24:11.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-06-21T11:25:40.000Z (over 5 years ago)
- Last Synced: 2025-02-02T03:26:13.900Z (9 months ago)
- Topics: combinations, leetcode, problem-solving
- Homepage:
- Size: 1000 Bytes
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Combinations
## https://leetcode.com/problems/combinationsGiven 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],
]
```
# Implementation : Recursive
```java
class Solution {
public List> combine(int n, int k) {
List> result = new ArrayList<>();
if (n <= 0 || n < k)
return result;
List item = new ArrayList();
dfs(n, k, 1, item, result); // because it need to begin from 1
return result;
}
private void dfs(int n, int k, int start, List item, List> res) {
if (item.size() == k) {
res.add(new ArrayList(item));
return;
}
for (int i = start; i <= n; i++) {
item.add(i);
dfs(n, k, i + 1, item, res);
item.remove(item.size() - 1); // removing the last added element
}
}
}
```