给定整数N ,任务是对N的有序整数分区中的数字进行计数。
例子:
Input: N = 3
Output: 8
Integer partitions of N(=3) are {{1 + 1 + 1}, {1 + 2}, {2 + 1}, {3}}.
Numbers in integer partition of N are:{1, 1, 1, 1, 2, 2, 1, 3}
Therefore, the count of numbers in integer partitions of N(=3) is 8.
Input: N = 4
Output: 20
方法:可以根据以下观察结果解决问题:
将N个分区精确地划分为k个分区的方法计数=
因此, N的有序整数分区中的数字计数为
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to count of numbers in
// ordered partitions of N
int CtOfNums(int N)
{
// Stores count the numbers in
// ordered integer partitions
int res = (N + 1) * (1 << (N - 2));
return round(res);
}
// Driver Code
int main()
{
int N = 3;
cout << CtOfNums(N);
}
// This code is contributed by code_hunt
Java
// Java program to implement
// the above approach
import java.io.*;
class GFG{
// Function to count of numbers in
// ordered partitions of N
static int CtOfNums(int N)
{
// Stores count the numbers in
// ordered integer partitions
int res = (N + 1) * (1 << (N - 2));
return Math.round(res);
}
// Driver Code
public static void main (String[] args)
{
int N = 3;
System.out.print(CtOfNums(N));
}
}
// This code is contributed by code_hunt
Python3
# Python3 program to implement
# the above approach
# Function to count of numbers in
# ordered partitions of N
def CtOfNums(N):
# Stores count the numbers in
# ordered integer partitions
res = (N + 1) * (1<<(N - 2))
return round(res)
# Driver code
if __name__ == '__main__':
N = 3
print(CtOfNums(N))
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to count of numbers in
// ordered partitions of N
static int CtOfNums(int N)
{
// Stores count the numbers in
// ordered integer partitions
double res = (N + 1) * (1 << (N - 2));
return (int)Math.Round(res);
}
// Driver Code
public static void Main ()
{
int N = 3;
Console.Write(CtOfNums(N));
}
}
// This code is contributed by code_hunt
Javascript
输出:
8
时间复杂度: O(log 2 N)
辅助空间: O(1)