Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Please code in Java Implement a method that takes an array of positive integers and a target integer. Return true if it is possible to

Please code in Java

Implement a method that takes an array of positive integers and a target integer. Return true if it is possible to place a + or - in front of every number and get a total equal to the target number. If the array is empty a false should always be returned regardless of the target value.

//DO NOT CHANGE THE METHOD HEADER

//You may implement any additional helper methods

//if you need them.

public static boolean addSub(int numbers[], int target) {

return false;

}

Example

Input - [1, 2, 3, 4], -2 Output - true

Reason - 1 - 2 + 3 - 4 = -2

Input - [7, 1, 3, 5], 9 Output - false

Reason - No combination of + or - will result in a value of 9.

This problem is a decision problem which requires us to try every possible combination of adding or subtracting each value. Each choice should be a recursive call that either adds the value or subtracts the value. The base case will occur once a decision is made for each number and returned should be true or false if the total is equal to the target. The pseudocode looks like the following

add_sub(array, index + 1, total + array[index], target) //This adds the integer to total add_sub(array, index + 1, total - array[index], target) //This subtracts the integer from total

This is a slight modification of the sum problem from the lab but instead of ignoring values as your second recursive call you are subtracting it from a total.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions