2597. The Number of Beautiful Subsets

题目 #

You are given an array nums of positive integers and a positive integer k.

A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k.

Return the number of non-empty beautiful subsets of the array nums.

A subset of nums is an array that can be obtained by deleting some (possibly none) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.

Example 1:

Input: nums = [2,4,6], k = 2
Output: 4
Explanation: The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].
It can be proved that there are only 4 beautiful subsets in the array [2,4,6].

Example 2:

Input: nums = [1], k = 1
Output: 1
Explanation: The beautiful subset of the array nums is [1].
It can be proved that there is only 1 beautiful subset in the array [1].

Constraints:

  • 1 <= nums.length <= 20
  • 1 <= nums[i], k <= 1000

思路1 枚举 #

分析 #

  • 使用hash表存储是否选了某个数,然后直接枚举

代码 #

 1func beautifulSubsets(nums []int, k int) int {
 2	result := make(map[int]int)
 3	res := 0
 4	n := len(nums)
 5	var dfs func(i int)
 6	dfs = func(i int) {
 7		if i == n {
 8			res++
 9			return
10		}
11		// 不选
12		dfs(i + 1)
13		v := nums[i]
14		if result[v-k] > 0 || result[v+k] > 0 {
15			// 存在间隔为k的数
16			return
17		}
18		// 可以选就选一下
19		result[v]++
20		dfs(i + 1)
21		result[v]--
22	}
23	dfs(0)
24	return res - 1 // 去除空集
25}

思路2 分组+打家劫舍 #

分析 #

  • 分成公差为k的等差数列,看有多少组
  • 相邻的不能选,非相邻的可以选,那么就是打家劫舍的变形

代码 #

 1func beautifulSubsets1(nums []int, k int) int {
 2	grp := make([]map[int]int, k)
 3	for _, v := range nums {
 4		i := v % k
 5		if grp[i] == nil {
 6			grp[i] = map[int]int{}
 7		}
 8		grp[i][v]++
 9	}
10
11	res := 1
12	type pair struct {
13		x, cnt int
14	}
15	for _, v := range grp {
16		if len(v) == 0 {
17			continue
18		}
19
20		arr := make([]pair, 0, len(v))
21		for k, val := range v {
22			arr = append(arr, pair{x: k, cnt: val})
23		}
24		sort.Slice(arr, func(i, j int) bool { return arr[i].x < arr[j].x })
25
26		// 打家劫舍,选和不选分开统计
27		ch, nch := 1<<arr[0].cnt-1, 1
28		for i := 1; i < len(arr); i++ {
29			ch1 := 1<<arr[i].cnt - 1	// 当前选的方案数
30			if arr[i].x-k == arr[i-1].x {
31				ch1 *= nch	// 相差为k,当前选的只能是前一个不选的数量乘以选的方案数
32			} else {
33				ch1 *= (ch + nch)	// 相差不是k,那么当前选的方案数就是前一个选和不选一起乘以当前的方案数
34			}
35			nch = ch + nch	// 不选的一定是前一个选和不选相加
36			ch = ch1
37		}
38		res *= (ch + nch)
39	}
40	return res - 1 // 去除空集
41}