L25 Backtracking Sum of Subset Problem

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

DAA (Unit-5)

Solving problems using


Backtracking

Sum of subset problem

By
Dr. Ratnesh Litoriya
Medi-Caps University, Indore (M.P.)
5/6/2023
Backtracking
Backtracking is a technique used to solve
problems with a large search space, by
systematically trying and eliminating
possibilities.
 It uses recursive calling to find the solution
by building a solution step by step increasing
values with time. It removes the solutions that
doesn't give rise to the solution of the
problem based on the constraints given to
solve the problem.
2
Sum of subset problem
Subset sum problem is to find subset of
elements that are selected from a given
set whose sum adds up to a given number
K.
We are considering the set contains non-
negative values.
It is assumed that the input set is unique
(no duplicates are presented).
Sum of subset problem
Example 1:
Given the following set of positive numbers:
{ 2, 9, 10, 1, 99, 3}
We need to find if there is a subset for a given sum say 4:
{ 1, 3 }
For another value say 5, there is another subset:
{ 2, 3}
Similarly, for 6, we have {2, 1, 3} as the subset.
For 7, there is no subset where the sum of elements equal
to 7.
Sum of subset problem
Example 2:
 Set: {10, 7, 5, 18, 12, 20, 15}
Sum: 30
 Output: [ {10, 5, 15}, {10, 20}, {7, 5, 18}, {18, 12} ]
 There are two ways to solve the Subset Sum Problem:
 Brute Force – Slow
 Backtracking – Fast
 In the Bruteforce approach, we usually test every
combination starting from one, then two, then three, and
so on for the required sum.
Sum of subset problem
Using exhaustive search we consider all
subsets irrespective of whether they
satisfy given constraints or not.
Backtracking can be used to make a
systematic consideration of the elements
to be selected.
The backtracking approach generates all
permutations in the worst case but in
general, performs better than the recursive
approach towards subset sum problem.
Sum of subset problem
Steps:
1. Start with an empty set
2. Add the next element from the list to the set
3. If the subset is having sum M, then stop with that subset
as solution.
4. If the subset is not feasible or if we have reached the
end of the set, then backtrack through the subset until
we find the most suitable value.
5. If the subset is feasible (sum of seubset < M) then go to
step 2.
6. If we have visited all the elements without finding a
suitable subset and if no backtracking is possible then
stop without solution.
Sum of subset problem
(Pseudo code)
Sum of subset problem
Time Complexity

Complexity
 Worst case time complexity: Θ(2^n)
 Space complexity: Θ(1)

You might also like