给定一个大小为N的不同整数数组arr[]和一个整数K ,任务是计算数组大小为 K的子集的数量,其元素的乘积可以表示为a 2 – b 2 。
例子:
Input: arr[] = {1, 2, 3} K = 2
Output: 2
Explaination:
All possible subsets of length 2 with their products are given below:
{1, 2} = 2
{2, 3} = 6
{1, 3} = 3
Since, only 3 can be expressed as (22 – 12, therefore only one such subset exists.
Input: arr[] = {2, 5, 6} K = 2
Output: 2
Explaination:
All possible contiguous sub-sequences with their products given below:
{2, 5} = 10
{2, 6} = 12
{5, 6} = 30
Since, only 12 can be expressed as (42 – 22), only one such subset exists.
方法:
- 生成大小为K 的所有子集。
- 计算所有子集的乘积。
- 只有当一个数是奇数或能被 4 整除时,才能表示为两个数的平方差。
- 因此,用满足此条件的乘积计算所有子集。
下面是上述方法的实现:
Python3
# Python3 implementation of the approach
import itertools
# Function to return the
# Count of required sub-sequences
def count_seq(arr, n, k):
# ans is Count variable
ans = 0
for seq in itertools.combinations(arr, k):
# product of seq
pro = 1
for ele in seq:
pro *= ele
# checking form of a2-b2
if ((pro % 4) != 2):
ans += 1
return ans
# Driver code
if __name__ == "__main__":
arr = [2, 5, 6]
n = len(arr)
k = 2
print(count_seq(arr, n, k))
输出:
1
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live