I want to make java program that count all unique possible ways from specific data (array list) given of an integer.
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
Your question is unclear, but I think what you're asking is "count the number of ways to add up to y
using only a set of numbers as possible summands".
I assume that the numbers in the second line are all distinct, are all less than y
(well, this is not really necessary), and are positive.
One solution is to use a recursive approach. Say f(y, {x_1, ..., x_n})
is the number of ways to add up to y
using only x_i
's.
Then f(y, {x_1, ..., x_n}) = sum of f(y - x_i, {x_1, ..., x_n}) for i = 1, ..., n
.
You can write a recursive function now. What's the base case? Well, y
could be 0, so the answer would be 1. Or y
could be negative, and the answer would be 0.
That should do it. But it will probably be very inefficient. I encourage you to read up on recursion and calculating Fibonacci numbers to learn how you can be more efficient (hint: memoization, and a bottoms-up approach instead of a top-down approach are your friends).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.