c# - 如何制作一个代码,为数字 x 生成所有整数分区,其中 y 作为 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来说太慢了,就用数组或列表来存储早期的结果,那只是“技术”。
推荐阅读
- python - Python打开html文件但不知道如何用不同的名称另存为
- angular - 可观察的
不能正常工作 - jquery - 使用对话框,等待响应,然后保存(或不保存)数据 - jquery
- angular - 如何使用角度读取 Apollo 客户端中的缓存
- react-native - React Native 获取 Firebase 数据库推送令牌密钥
- python-3.x - AttributeError 尝试在 Python 中使用 Selenium 自动化 WhatsApp
- c++ - 我可以分配一个指针对象数组=另一个对象吗?
- python - 正则表达式跨越多行
- python - ElementNotInteractableException:消息:元素不可交互:元素当前不可见,可能无法使用机器人框架进行操作
- python - 根据索引合并两个系列