[go: up one dir, main page]

0% found this document useful (0 votes)
9 views2 pages

subset_sum_backtracking

The document describes the Subset Sum Problem, which aims to find a subset of integers that sums to a given target. It outlines a backtracking algorithm with pseudocode and provides an example demonstrating the process. The time complexity is O(2^n) and the space complexity is O(n), emphasizing the importance of pruning when the current sum exceeds the target.

Uploaded by

ROHIT DADHWAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

subset_sum_backtracking

The document describes the Subset Sum Problem, which aims to find a subset of integers that sums to a given target. It outlines a backtracking algorithm with pseudocode and provides an example demonstrating the process. The time complexity is O(2^n) and the space complexity is O(n), emphasizing the importance of pruning when the current sum exceeds the target.

Uploaded by

ROHIT DADHWAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Subset Sum Problem using Backtracking

Problem Statement:
-------------------
Given a set of integers and a target sum, find whether there exists a subset whose
sum is equal to the target sum.

Algorithm (Pseudocode):
------------------------
Function SubsetSum(arr, n, target_sum):
Call backtrack(0, 0)

Function backtrack(index, current_sum):


if current_sum == target_sum:
return True
if index == n or current_sum > target_sum:
return False

// Choice 1: Include arr[index] in the subset


if backtrack(index + 1, current_sum + arr[index]):
return True

// Choice 2: Exclude arr[index] from the subset


if backtrack(index + 1, current_sum):
return True

return False

Example:
---------
Input:
- Array = [3, 34, 4, 12, 5, 2]
- Target Sum = 9

Execution Steps:
- Start from index = 0, current_sum = 0
- Include 3 → current_sum = 3
- Exclude 34
- Include 4 → current_sum = 7
- Exclude 12
- Exclude 5
- Include 2 → current_sum = 9 → FOUND

Subset: [3, 4, 2]

Search Tree (Partial):


----------------------
(0,0)
/ \
include 3 (1,3) exclude 3 (1,0)
/ \
include 34 (2,37) exclude 34 (2,3)
X / \
(too big)...

Where (index, current_sum)


X = dead-end
Time and Space Complexity:
---------------------------
- Time Complexity: O(2^n) (Exponential, tries all subsets)
- Space Complexity: O(n) (Recursion depth)

Summary:
---------
Aspect | Value
--------------------|----------------------
Time Complexity | O(2^n)
Space Complexity | O(n)
Type | Exponential, Backtracking
Important | Prune when sum > target

You might also like