Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find subsets with a given sum

Find all unique subsets of a list of non-negative integers that sum to a target. Each number may be used at most once.

Python practice16 minRecursion & BacktrackingIntermediateLast updated March 27, 2026

Problem statement

Given a list of non-negative integers nums and a non-negative integer target, return all unique subsets (each subset is a list of integers) where the sum of elements equals target. Each number in nums may be used at most once. The result should not contain duplicate subsets (treat subsets with the same values in a different order as identical). Return the list of subsets sorted lexicographically (compare by element values). If target is 0, return a list containing the empty subset: [[]].

Task

Use backtracking and careful handling of duplicates to enumerate unique subsets whose elements sum to the target.

Examples

Two ways to make 5

Input

nums = [2,3,5], target = 5

Output

[[2, 3], [5]]

Subsets [2,3] and [5] sum to 5. Returned list sorted lexicographically.

Input format

A list of non-negative integers nums and an integer target (>= 0).

Output format

A list of unique subsets (each a list of integers). The list and each subset are sorted lexicographically/ascending.

Constraints

- 0 <= len(nums) <= 20 - 0 <= nums[i] <= 50 - 0 <= target <= 1000 - Use backtracking; sort and skip duplicates to avoid repeated subsets

Samples

Sample 1

Input

nums = [2,4,6,3], target = 6

Output

[[2, 4], [6]]

Two subsets sum to 6: [2,4] and [6].