📌  相关文章
📜  从 1 到 N 没有相邻元素的整数子集的计数

📅  最后修改于: 2021-09-03 15:07:03             🧑  作者: Mango

给定一个整数N ,任务是计算从1N不包含相邻元素的整数数组形成的子集的数量。满足不相邻元素条件的子集不能被选择,但可以添加更多元素。
例子:

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 Classes Live