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

Commit866b757

Browse files
MEDIUM/src/medium/Permutations.java using regular recursive method
1 parent47eea51 commit866b757

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

‎MEDIUM/src/medium/Permutations.java

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
packagemedium;
2+
importjava.util.ArrayList;
3+
importjava.util.List;
4+
5+
publicclassPermutations {
6+
staticclassAccepted_solution {
7+
//this solution has a recursive function that has a return type
8+
publicstaticList<List<Integer>>permute(int[]nums) {
9+
List<List<Integer>>result =newArrayList();
10+
result.add(newArrayList<>());
11+
returnrecursive(result,nums,0);
12+
}
13+
14+
privatestaticList<List<Integer>>recursive(List<List<Integer>>result,int[]nums,
15+
intpos) {
16+
if (pos ==nums.length)
17+
returnresult;
18+
List<List<Integer>>newResult =newArrayList();
19+
for (List<Integer>eachList :result) {
20+
for (inti =0;i <=eachList.size();i++) {
21+
List<Integer>newList =newArrayList(eachList);
22+
newList.add(i,nums[pos]);
23+
newResult.add(newList);
24+
}
25+
}
26+
result =newResult;
27+
returnrecursive(result,nums,pos +1);
28+
}
29+
}
30+
31+
staticclassAccepted_solution_with_void_type {
32+
publicstaticList<List<Integer>>permute(int[]nums) {
33+
List<List<Integer>>result =newArrayList();
34+
result.add(newArrayList<>());
35+
recursive(result,nums,0);
36+
returnresult;
37+
}
38+
39+
privatestaticvoidrecursive(List<List<Integer>>result,int[]nums,intpos) {
40+
if(pos ==nums.length)return;
41+
List<List<Integer>>newResult =newArrayList();
42+
for(List<Integer>eachList :result){
43+
for(inti =0;i <=eachList.size();i++){
44+
List<Integer>newList =newArrayList(eachList);
45+
newList.add(i,nums[pos]);
46+
newResult.add(newList);
47+
}
48+
}
49+
/**You'll have to use the two lines, instead of this line: result = newResult; otherwise, it won't work!!! Fuck!*/
50+
result.clear();
51+
result.addAll(newResult);
52+
53+
//then recursion
54+
recursive(result,nums,pos+1);
55+
}
56+
}
57+
58+
publicstaticvoidmain(String...args){
59+
int[]nums =newint[]{1,2,2};
60+
}
61+
62+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp