如何编写代码生成数字 x 的所有整数分区,其中 y 作为 C# 分区中可用的最大数字
How to make a code which generates all integer partitions for number x, which has y as the largest number usable in the partition in C#
例如,输入“5 3”得到5作为分区数(3+2, 3+1+1, 2+2+1, 2+1+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太慢,就用数组或者列表来存
较早的结果,只是 "technics".
例如,输入“5 3”得到5作为分区数(3+2, 3+1+1, 2+2+1, 2+1+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太慢,就用数组或者列表来存 较早的结果,只是 "technics".