Input: digits =[2,1,3,0]Output: [102,120,130,132,210,230,302,310,312,320]Explanation: All the possible integers that follow the requirements are in the output array.Notice that there are no **odd** integers or integers with**leading zeros**.
Input: digits =[2,2,8,8,2]Output: [222,228,282,288,822,828,882]Explanation: The same digit can be used as many times as it appears in digits.In this example, the digit 8is used twice each time in288,828, and 882.
To address the problem, let’s break it into steps:
Generate combinations: Create all possible combinations of three distinct digits from the given array.
Concatenate digits: For each combination, concatenate the digits in all possible orders. This results in integers formed by concatenating three digits.
Check requirements:
Ensure integers do not have leading zeros.
Ensure integers are even (last digit is divisible by 2).
Remove duplicates: Use a set data structure to ensure uniqueness of integers.
Sort the result: Return the sorted list of integers.
classSolution {
publicint[]findEvenNumbers(int[] digits) {
Set<Integer> ans =new HashSet<>(); // Store unique integersint n = digits.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
if (i != j && j != k && i != k) { // Ensure distinct indicesint num = digits[i]* 100 + digits[j]* 10 + digits[k];
if (digits[i]!= 0 && num % 2 == 0) { // No leading zero and even ans.add(num);
}
}
}
}
}
int[] result = ans.stream().sorted().mapToInt(x -> x).toArray(); // Convert set to sorted arrayreturn result;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
deffindEvenNumbers(self, digits: List[int]) -> List[int]:
from itertools import permutations
ans: set[int] = set() # Store unique integers n = len(digits)
for i in range(n):
for j in range(n):
for k in range(n):
if i != j and j != k and i != k: # Ensure distinct indices num = digits[i] *100+ digits[j] *10+ digits[k]
if digits[i] !=0and num %2==0: # No leading zero and even ans.add(num)
return sorted(ans)