← 返回 apple 的题目列表All Subsets with a Given Sum
类型:online_judge
Problem: All Subsets with a Given Sum
Given an array arr of distinct positive integers and a non-negative integer target, find all subsets whose elements sum to exactly target.
Each array element can be used at most once.
Implement the solution using Backtracking.
Input Format
n target
arr[0] arr[1] ... arr[n-1]
Output Format
Print all subsets whose sum is equal to target.
To make the output deterministic and testable:
Elements inside each subset should be printed in ascending order.
All subsets should be printed in lexicographical order.
The first line should contain the number of subsets k.
The next k lines each contain one subset, with elements separated by spaces.
If a subset is empty, print [].
Constraints
0 <= n <= 25
0 <= target <= 100000
1 <= arr[i] <= 100000
Elements in arr are distinct.
Requirements
Use backtracking to enumerate possible subsets.
Analyze the time complexity as O(2^n) level.
Analyze the space complexity, including recursion stack and output storage.
Example
Input:
5 5
1 2 3 4 5
Output:
3
1 4
2 3
5
Example
Input
5 5
1 2 3 4 5
Output
3
1 4
2 3
5