如何制作一个代码,为数字 x 生成所有整数分区,其中 y 是 C# 中分区中可用的最大数字



例如,输入"5 3"给出5作为分区数(3+2,3+1+1,2+2+1,2+1+1+1,1+1+1+1(,不包括5或4+1,因为它们包含大于y的整数。

我还没有发现参数 x 和 y 与输出之间存在任何相关性。 这是我到目前为止设法制作的代码。它检测包含 1 和单个其他数字的潜在组合。到目前为止,我还没有找到一种方法来让它检测到大于 1 的多个数字。

class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
string[] inputs = input.Split();
int max = Convert.ToInt32(inputs[0]);
int amount = Convert.ToInt32(inputs[1]);
int path = max;
int how_many = 1; // said one is 1+1+1...
int x = 2;
while (x <= amount)
{
while (path >= x) //only 1 and another number
{
path -= x;
how_many += 1;
}
path = max;
x += 1;
}
Console.WriteLine(how_many);
Console.ReadKey();
}

抱歉,不是 C#,而是 python3 解决方案(递归(,适用于 C# 只是我不是 Windows 粉丝:

def solution(n, m):
if n < 2 or m < 2:
return 1
if n < m:
return solution(n, n)  ## or m = n
return solution(n-m, m) + solution(n, m-1)
print(solution(5, 3))
#5
print(solution(8,4))
#15
#4+4, 4+3+1, 4+2+2, 4+2+1+1, 4+1+1+1+1
#3+3+2 3+3+1+1 3+2+2+1 3+2+1+1+1 3+1+1+1+1+1
#2+2+2+2  2+2+2+1+1 2+2+1+1+1+1 2+1+1+1+1+1+1 1+1+1+1+1+1+1+1+1

如果对于大 N 和 M 来说太慢了,只需使用数组或列表来存储 早期的结果,只是"技术"。

最新更新