educative.io

Educative

I think the recursive solution can be more concise

Something like this:

public static List<HashSet<Integer>> getKSumSubsets(List<Integer> setOfIntegers, Integer targetSum) {
		
		if(setOfIntegers == null || setOfIntegers.isEmpty() || targetSum == null) {
			return Collections.emptyList();
		}

		List<HashSet<Integer>> subsets = new ArrayList<HashSet<Integer>>();

		comb(subsets, new LinkedList<>(), setOfIntegers, 0, targetSum);

		return subsets;
	}


	private static void comb(List<HashSet<Integer>> res, 
								LinkedList<Integer> acc, 
								List<Integer> nums,
								int start, int n) {

		if(n <= 0) {
			if(n == 0) {
				res.add(new HashSet(acc));
			}
			return;
		}

		for(int i = start; i < nums.size(); i++) {
			acc.add(nums.get(i));
			comb(res, acc, nums, i + 1, n - nums.get(i));
			acc.removeLast();
		}
	}

Type your question above this line.

Course: https://www.educative.io/collection/5642554087309312/5679846214598656
Lesson: https://www.educative.io/collection/page/5642554087309312/5679846214598656/120002

Hi @Peter_Litvak, Thank you for your solution. There can be multiple ways of solving a single problem but if we consider an optimized solution in terms of space complexity that would be the iterative solution.