Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitacf5d3f

Browse files
committed
Create Combinations.java
Problem statement: Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example, If n = 4 and k = 2, a solution is: [[2,4], [3,4], [2,3], [1,2], [1,3], [1,4]]Strategy: Determin the starting number `start` among all k numbers as a first step. Afterwards, repeat the same problem by changing k to k-1 and changing possible starting number from `start` to `start+1`
1 parent8cfe703 commitacf5d3f

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

‎DFS/Combinations.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
Problem statement: Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example, If n = 4 and k = 2, a solution is: [[2,4], [3,4], [2,3], [1,2], [1,3], [1,4]]
3+
Strategy: Determin the starting number `start` among all k numbers as a first step. Afterwards, repeat the same problem by changing k to k-1 and changing possible starting number from `start` to `start+1`
4+
*/
5+
6+
publicList<List<Integer>>combine(intn,intk) {
7+
List<List<Integer>>res =newLinkedList<>();
8+
if(k>n)returnres;
9+
helper(n,k,1,newLinkedList<Integer>(),res);
10+
returnres;
11+
}
12+
privatevoidhelper(intn,intk,intstart,List<Integer>list,List<List<Integer>>res) {
13+
if(k==1) {
14+
for(inti=start;i<=n;i++) {
15+
List<Integer>inner =newLinkedList<Integer>(list);
16+
inner.add(i);
17+
res.add(inner);
18+
}
19+
return;
20+
}
21+
for(inti=start;i<=n-k+1;i++) {
22+
List<Integer>inner =newLinkedList<Integer>(list);
23+
inner.add(i);
24+
helper(n,k-1,i+1,inner,res);
25+
}
26+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp