Skip to content

Commit ca51650

Browse files
committedJul 26, 2023
Time: 2 ms (48.55%), Space: 44.1 MB (47.73%) - LeetHub
1 parent 0a3a9a7 commit ca51650

File tree

1 file changed

+25
-20
lines changed

1 file changed

+25
-20
lines changed
 

Diff for: ‎0046-permutations/0046-permutations.java

+25-20
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,28 @@
11
class Solution {
2-
public List<List<Integer>> permute(int[] nums) {
3-
List<List<Integer>> list = new ArrayList<>();
4-
// Arrays.sort(nums); // not necessary
5-
backtrack(list, new ArrayList<>(), nums);
6-
return list;
7-
}
8-
9-
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums){
10-
if(tempList.size() == nums.length){
11-
list.add(new ArrayList<>(tempList));
12-
} else{
13-
for(int i = 0; i < nums.length; i++){
14-
if(tempList.contains(nums[i])) continue; // element already exists, skip
15-
tempList.add(nums[i]);
16-
backtrack(list, tempList, nums);
17-
tempList.remove(tempList.size() - 1);
18-
}
19-
}
20-
}
21-
2+
public List<List<Integer>> permute(int[] nums) {
3+
List<List<Integer>> res = new ArrayList<>();
4+
List<Integer> temp = new ArrayList<>();
5+
6+
backtracker(res, temp, nums);
7+
return res;
8+
9+
}
10+
private void backtracker(List<List<Integer>> res, List<Integer> temp, int[] nums){
11+
12+
if(temp.size() == nums.length){
13+
14+
res.add(new ArrayList<>(temp));
15+
}
16+
else{
17+
18+
for(int i = 0 ; i < nums.length; i++){
19+
if(temp.contains(nums[i])) continue;
2220

21+
temp.add(nums[i]);
22+
backtracker(res, temp, nums);
23+
temp.remove(temp.size() - 1);
24+
}
25+
}
26+
27+
}
2328
}

0 commit comments

Comments
 (0)