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

Commitc6366ce

Browse files
add a solution for 46
1 parenta962eed commitc6366ce

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

‎src/main/java/com/fishercoder/solutions/_46.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,33 @@ private void backtracking(List<Integer> list, int[] nums, Set<List<Integer>> ans
6868
}
6969
}
7070

71+
publicstaticclassSolution3 {
72+
/**
73+
* A more efficient version of backtracking.
74+
*/
75+
publicList<List<Integer>>permute(int[]nums) {
76+
List<List<Integer>>ans =newArrayList<>();
77+
boolean[]used =newboolean[nums.length];
78+
returnbacktracking(ans,used,newArrayList<>(),nums);
79+
}
80+
81+
privateList<List<Integer>>backtracking(List<List<Integer>>ans,boolean[]used,List<Integer>list,int[]nums) {
82+
if (list.size() ==nums.length) {
83+
ans.add(newArrayList<>(list));
84+
returnans;
85+
}
86+
for (inti =0;i <nums.length;i++) {
87+
if (used[i]) {
88+
continue;
89+
}
90+
used[i] =true;
91+
list.add(nums[i]);
92+
backtracking(ans,used,list,nums);
93+
used[i] =false;
94+
list.remove(list.size() -1);
95+
}
96+
returnans;
97+
}
98+
}
99+
71100
}

‎src/test/java/com/fishercoder/_46Test.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,26 @@
88
publicclass_46Test {
99
privatestatic_46.Solution1solution1;
1010
privatestatic_46.Solution2solution2;
11+
privatestatic_46.Solution3solution3;
1112

1213
@BeforeClass
1314
publicstaticvoidsetup() {
1415
solution1 =new_46.Solution1();
1516
solution2 =new_46.Solution2();
17+
solution3 =new_46.Solution3();
1618
}
1719

1820
@Test
1921
publicvoidtest1() {
2022
CommonUtils.printListList(solution1.permute(newint[]{1,2,3}));
2123
CommonUtils.printListList(solution2.permute(newint[]{1,2,3}));
24+
CommonUtils.printListList(solution3.permute(newint[]{1,2,3}));
2225
}
2326

2427
@Test
2528
publicvoidtest2() {
2629
CommonUtils.printListList(solution1.permute(newint[]{1,2,3,4,5,6}));
2730
CommonUtils.printListList(solution2.permute(newint[]{1,2,3,4,5,6}));
31+
CommonUtils.printListList(solution3.permute(newint[]{1,2,3,4,5,6}));
2832
}
2933
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp