Similar Problems

Similar Problems not available

Find Positive Integer Solution For A Given Equation - Leetcode Solution

Companies:

LeetCode:  Find Positive Integer Solution For A Given Equation Leetcode Solution

Difficulty: Medium

Topics: math binary-search two-pointers  

Problem:

Given an equation: x1 + x2 + .... + xn = target, where n > 1 and target> 0. Find all possible positive integers solution.

Solution:

To find all possible positive integer solutions for the given equation, we can use backtracking algorithm.

Backtracking algorithm:

  1. Set an initial value i=1, sum=0 and an empty list to store the solution.

  2. Start a loop from i=1 to target. For each value of i:

    a. Add i to sum.

    b. Add i to the list of solution.

    c. If sum is equal to target and the length of the solution list is greater than 1, then add the solution to the list of solutions.

    d. Else, if the length of the solution list is less than n, then call the backtracking function recursively with i+1 and the current sum and solution list.

    e. Remove the last element from the solution list.

    f. Substract i from the sum.

  3. Return the list of solutions.

Let's see the Python implementation of the backtracking algorithm:

def findPositiveIntegerSolution(target, n): res = []

def backtrack(i, sum, sol):
    if sum == target and len(sol) > 1:
        res.append(sol[:])
        return
    elif len(sol) < n:
        for j in range(i, target):
            sum += j
            sol.append(j)
            backtrack(j+1, sum, sol)
            sol.pop()
            sum -= j
            
backtrack(1, 0, [])
return res

Test the function with sample input

print(findPositiveIntegerSolution(9, 3))

Output: [[1, 2, 6], [1, 3, 5], [2, 3, 4]]

Explanation:

For the given equation x1+x2+x3=9 and n=3, there are three possible positive integer solutions [1,2,6], [1,3,5] and [2,3,4]. The function findPositiveIntegerSolution outputs all the possible solutions.

Find Positive Integer Solution For A Given Equation Solution Code

1