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

Appearance settings

Latest commit

 

History

History
History
37 lines (33 loc) · 955 Bytes

File metadata and controls

37 lines (33 loc) · 955 Bytes
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
package leetcode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/*
1...n 中的k个数的全排列
* */
public class leetcode77 {
private List<List<Integer>> res = new ArrayList<>();
/*
pre 用来记录寻找中的组合,长度从1到k
* */
private void findCombinations(int n, int k, int begin, Stack<Integer> pre) {
if (pre.size()==k){
res.add(new ArrayList<>(pre));
}
for (int i = begin; i <=n; i++) {
pre.add(i);
findCombinations(n,k,i+1,pre); //向下递归 begin 为i+1
pre.pop(); //回溯
}
}
public List<List<Integer>> combine(int n, int k) {
if (n <= 0 || k <= 0 || n < k) {
return res;
}
findCombinations(n,k,1,new Stack<>());
return res;
}
public static void main(String[] args) {
System.out.println(new leetcode77().combine(4,2));
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.