给定整数N ,任务是计算从1到N的整数数组形成的子集的数量,该子集不包含相邻元素。如果满足不相邻元素条件,则无法选择子集,但是可以添加更多元素。
例子:
Input: N = 4
Output: 3
Explanation:
Array is {1, 2, 3, 4}
So to satisfy the condition, the subsets formed are :
{1, 3}, {2, 4}, {1, 4}
Input: N = 5
Output: 4
方法:
通过使用动态编程可以解决此问题。对于最后一个元素,我们有两个选择,要么包含它,要么排除它。令DP [i]为以索引i结尾的期望子集的数量。
所以下一个子问题变成DP [i-3]
因此,DP关系变为:
DP[i] = DP[i-2] + DP[i-3]
但是,我们需要观察基本情况:
- 当N = 0时,我们不能形成任何具有0个数字的子集。
- 当N = 1时,我们可以形成1个子集{1}
- 当N = 2时,我们可以形成2个子集{1} , {2}
- 当N = 3时,我们可以形成2个子集{1,3} , {2}
下面是上述方法的实现:
C++
// C++ Code to count subsets not containing
// adjacent elements from 1 to N
#include
using namespace std;
// Function to count subsets
int countSubsets(int N)
{
if(N <= 2)
return N;
if(N == 3)
return 2;
int DP[N + 1] = {0};
DP[0] = 0, DP[1] = 1, DP[2] = 2, DP[3] = 2;
for (int i = 4; i <= N; i++) {
DP[i] = DP[i - 2] + DP[i - 3];
}
return DP[N];
}
// Driver Code
int main()
{
int N = 20;
cout << countSubsets(N);
return 0;
}
Java
// Java code to count subsets not containing
// adjacent elements from 1 to N
class GFG{
// Function to count subsets
static int countSubsets(int N)
{
if(N <= 2)
return N;
if(N == 3)
return 2;
int []DP = new int[N + 1];
DP[0] = 0;
DP[1] = 1;
DP[2] = 2;
DP[3] = 2;
for(int i = 4; i <= N; i++)
{
DP[i] = DP[i - 2] + DP[i - 3];
}
return DP[N];
}
// Driver code
public static void main(String[] args)
{
int N = 20;
System.out.print(countSubsets(N));
}
}
// This code is contributed by sapnasingh4991
Python3
# Python3 Code to count subsets
# not containing adjacent elements
# from 1 to N
# Function to count subsets
def countSubsets(N):
if(N <= 2):
return N
if(N == 3):
return 2
DP = [0] * (N + 1)
DP[0] = 0
DP[1] = 1
DP[2] = 2
DP[3] = 2
for i in range(4, N + 1):
DP[i] = DP[i - 2] + DP[i - 3]
return DP[N]
# Driver Code
if __name__ == '__main__':
N = 20
print(countSubsets(N))
# This code is contributed by Mohit Kumar
C#
// C# code to count subsets not containing
// adjacent elements from 1 to N
using System;
class GFG{
// Function to count subsets
static int countSubsets(int N)
{
if(N <= 2)
return N;
if(N == 3)
return 2;
int []DP = new int[N + 1];
DP[0] = 0;
DP[1] = 1;
DP[2] = 2;
DP[3] = 2;
for(int i = 4; i <= N; i++)
{
DP[i] = DP[i - 2] + DP[i - 3];
}
return DP[N];
}
// Driver code
public static void Main(String[] args)
{
int N = 20;
Console.Write(countSubsets(N));
}
}
// This code is contributed by sapnasingh4991
Javascript
输出:
265
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。