FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-Interview/Combinations.java at master · arjunmullick/coding-Interview · GitHub
arjunmullick
/
coding-Interview
Public
Notifications
You must be signed in to change notification settings
Fork
1
Star
3
Code
Issues
0
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-Interview
/
Combinations.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
38 lines (31 loc) · 1.1 KB
Breadcrumbs
coding-Interview
/
Combinations.java
Copy path
File metadata and controls
38 lines (31 loc) · 1.1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package
com
.
leetcode
;
import
java
.
util
.
ArrayList
;
import
java
.
util
.
List
;
public
class
Combinations
{
//https://leetcode.com/problems/combinations/
/**
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.
Time complexity: O(2^n)
Space complexity: O(n)
**/
class
Solution
{
public
List
<
List
<
Integer
>>
combine
(
int
n
,
int
k
) {
List
<
List
<
Integer
>>
result
=
new
ArrayList
<>();
backtrack
(
1
,
n
,
k
,
new
ArrayList
<>(),
result
);
return
result
;
}
public
void
backtrack
(
int
start
,
int
n
,
int
k
,
List
<
Integer
>
list
,
List
<
List
<
Integer
>>
result
){
if
(
list
.
size
() ==
k
){
result
.
add
(
new
ArrayList
<>(
list
));
}
for
(
int
i
=
start
;
i
<=
n
;
i
++){
list
.
add
(
i
);
backtrack
(
i
+
1
,
n
,
k
,
list
,
result
);
list
.
remove
(
list
.
size
()-
1
);
}
}
}
}
Back
|
FazBrowse Home
|
New Git URL