-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadmd
More file actions
122 lines (78 loc) · 2.07 KB
/
Readmd
File metadata and controls
122 lines (78 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# 🔍 Subset Sum using Backtracking
This project implements a **Backtracking algorithm** to find all subsets of a given list of integers (including both positive and negative numbers) whose sum equals a specified target value.
---
## Features
* Works with both **positive and negative integers**
* Finds **all possible subsets** that match the target sum
* Uses **recursive backtracking**
* Simple and easy-to-understand implementation
---
## Problem Statement
Given a list of integers (size up to 30), find all subsets whose sum is exactly equal to a target value provided by the user.
---
## Approach
* Use **backtracking** to explore all possible subsets
* At each step:
* Include the current element
* Recurse to the next element
* Backtrack (remove element)
* If the subset sum equals the target → store the subset
---
## Code
```python
def find_subsets(nums, target):
result = []
def backtrack(start, current_subset, current_sum):
if current_sum == target:
result.append(current_subset[:])
return
for i in range(start, len(nums)):
current_subset.append(nums[i])
backtrack(i + 1, current_subset, current_sum + nums[i])
current_subset.pop()
backtrack(0, [], 0)
return result
nums = list(map(int, input().split()))
target = int(input())
subsets = find_subsets(nums, target)
for s in subsets:
print(s)
```
---
## How to Run
1. Clone the repository
2. Run the Python file:
```bash
python subset_sum.py
```
3. Enter input:
* First line: integers separated by space
* Second line: target sum
---
## Example
### Input
```
1 -1 2 3 -2
3
```
### Output
```
[1, 2]
[3]
[1, -1, 3]
[2, 3, -2]
```
---
## Complexity
* **Time Complexity:** O(2^n)
* **Space Complexity:** O(n)
---
## Notes
* Suitable for small datasets (n ≤ 30)
* May take longer time for large inputs due to exponential complexity
---
## Future Improvements
* Optimize using **Meet-in-the-Middle**
* Add **Dynamic Programming approach**
* Improve performance with pruning techniques
---