【问题标题】:How to find all unique possible ways of partition from specific data given of an integer如何从给定整数的特定数据中找到所有唯一可能的分区方式
【发布时间】:2017-01-19 05:03:23
【问题描述】:

我想制作一个 java 程序,从给定整数的特定数据(数组列表)中计算所有唯一可能的方式。

Example :
input: 3 6
       1 2 3 
output: 7

explanation: the first line contains two separated integers of value x,y.
the second line contains x separated integers

For y = 6 and x = {1, 2, 3} there are exactly seven ways:
      
1. {1, 1, 1, 1, 1, 1} <— sum up to 6
      
2. {1, 1, 1, 1, 2} <- sum up to 6
3. {1, 1, 1, 3} <- sum up to 4
4. {2, 2, 2} <— sum up to 6
5. {2, 2, 1, 1} <— sum up to 6
6. {1, 2, 3} <— sum up to 6
7. {3, 3} <- sum up to 6

【问题讨论】:

标签: java


【解决方案1】:

您的问题不清楚,但我认为您要问的是“仅使用一组数字作为可能的加法数,计算加起来 y 的方法的数量”。

我假设第二行中的数字都是不同的,都小于y(嗯,这不是必需的),并且都是正数。

一种解决方案是使用递归方法。假设f(y, {x_1, ..., x_n}) 是仅使用x_iy 相加的方式数。

然后f(y, {x_1, ..., x_n}) = sum of f(y - x_i, {x_1, ..., x_n}) for i = 1, ..., n

您现在可以编写递归函数了。基本情况是什么?好吧,y 可能是 0,所以答案是 1。或者 y 可能是否定的,答案是 0。

应该这样做。但这可能会非常低效。我鼓励您阅读递归和计算斐波那契数,以了解如何提高效率(提示:记忆,以及自下而上的方法而不是自上而下的方法是您的朋友)。

【讨论】:

    猜你喜欢
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    相关资源
    最近更新 更多