You are given an integer array nums, which contains distinct elements and an integer k.
A subset is called a k-Free subset if it contains no two elements with an absolute difference equal to k. Notice that the empty set is a k-Free subset.
Return _the number ofk-Free subsets of _nums.
A subset of an array is a selection of elements (possibly none) of the array.
The key idea is to avoid picking two numbers whose difference is exactly k. By sorting the array and grouping numbers that are k apart, we can use dynamic programming to count valid subsets for each group independently, then multiply the results.
classSolution {
publiclongcountTheNumOfKFreeSubsets(int[] nums, int k) {
Arrays.sort(nums);
long ans = 1;
List<Integer>[] groups =new List[k];
for (int i = 0; i < k; i++) groups[i]=new ArrayList<>();
for (int x : nums) groups[x % k].add(x);
for (List<Integer> g : groups) {
int m = g.size();
if (m == 0) continue;
long[] dp =newlong[m + 1];
dp[0]= 1; dp[1]= 1;
for (int i = 1; i < m; i++) {
if (g.get(i) - g.get(i-1) == k) {
dp[i+1]= dp[i]+ dp[i-1];
} else {
dp[i+1]= dp[i]* 2;
}
}
ans *= dp[m];
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funcountTheNumOfKFreeSubsets(nums: IntArray, k: Int): Long {
nums.sort()
var ans = 1Lval groups = Array(k) { mutableListOf<Int>() }
for (x in nums) groups[x % k].add(x)
for (g in groups) {
val m = g.size
if (m ==0) continueval dp = LongArray(m + 1)
dp[0] = 1L; dp[1] = 1Lfor (i in1 until m) {
dp[i+1] = if (g[i] - g[i-1] == k) dp[i] + dp[i-1] else dp[i] * 2 }
ans *= dp[m]
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
defcountTheNumOfKFreeSubsets(self, nums: list[int], k: int) -> int:
nums.sort()
ans =1 groups: list[list[int]] = [[] for _ in range(k)]
for x in nums:
groups[x % k].append(x)
for g in groups:
m = len(g)
if m ==0:
continue dp = [1, 1]
for i in range(1, m):
if g[i] - g[i-1] == k:
dp.append(dp[-1] + dp[-2])
else:
dp.append(dp[-1] *2)
ans *= dp[-1]
return ans
impl Solution {
pubfncount_the_num_of_k_free_subsets(nums: Vec<i32>, k: i32) -> i64 {
letmut nums = nums;
nums.sort();
letmut ans =1i64;
letmut groups =vec![vec![]; k asusize];
for&x in&nums {
groups[(x % k) asusize].push(x);
}
for g in groups.iter() {
let m = g.len();
if m ==0 { continue; }
letmut dp =vec![1i64, 1];
for i in1..m {
if g[i] - g[i-1] == k {
dp.push(dp[i] + dp[i-1]);
} else {
dp.push(dp[i] *2);
}
}
ans *= dp[m];
}
ans
}
}