Skip to content

Commit 67f3544

Browse files
authored
Update readme.md
1 parent 1362317 commit 67f3544

File tree

1 file changed

+46
-1
lines changed
  • src/main/java/g0001_0100/s0046_permutations

1 file changed

+46
-1
lines changed

src/main/java/g0001_0100/s0046_permutations/readme.md

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,49 @@ Given an array `nums` of distinct integers, return all the possible permutations
2626

2727
* `1 <= nums.length <= 6`
2828
* `-10 <= nums[i] <= 10`
29-
* All the integers of `nums` are **unique**.
29+
* All the integers of `nums` are **unique**.
30+
31+
To solve the "Permutations" problem in Java with a `Solution` class, we can follow these steps:
32+
33+
1. Define a `Solution` class.
34+
2. Define a method named `permute` that takes an array of distinct integers `nums` as input and returns a list of all possible permutations.
35+
3. Create an empty list to store the result permutations.
36+
4. Call a recursive helper function named `permuteHelper` to generate permutations.
37+
5. Inside the `permuteHelper` function:
38+
- If the current permutation size equals the length of the input array `nums`, add a copy of the current permutation to the result list.
39+
- Otherwise, iterate through each element of `nums`:
40+
- If the current element is not already in the permutation, add it to the current permutation, and recursively call `permuteHelper` with the updated permutation and the remaining elements of `nums`.
41+
- After the recursive call, remove the last element from the permutation to backtrack.
42+
6. Return the result list.
43+
44+
Here's the implementation:
45+
46+
```java
47+
import java.util.ArrayList;
48+
import java.util.List;
49+
50+
public class Solution {
51+
public List<List<Integer>> permute(int[] nums) {
52+
List<List<Integer>> result = new ArrayList<>();
53+
permuteHelper(nums, new ArrayList<>(), result);
54+
return result;
55+
}
56+
57+
private void permuteHelper(int[] nums, List<Integer> current, List<List<Integer>> result) {
58+
if (current.size() == nums.length) {
59+
result.add(new ArrayList<>(current));
60+
return;
61+
}
62+
63+
for (int num : nums) {
64+
if (!current.contains(num)) {
65+
current.add(num);
66+
permuteHelper(nums, current, result);
67+
current.remove(current.size() - 1);
68+
}
69+
}
70+
}
71+
}
72+
```
73+
74+
This implementation provides a solution to the "Permutations" problem in Java. It generates all possible permutations of the given array of distinct integers using backtracking.

0 commit comments

Comments
 (0)