kSum Problem

Problem

Given an array S of n integers, are there elements a1, a2, a3…ak in S such that sum(a1, a2, a3, ... ak) = target? Find all unique lists in the array which gives the sum of target.

Examples

Refer problems like 4Sum, 3Sum - Classic Problem, 3Sum0 - Find three elements in an array that sum to a zero for examples.

Solution

Method 1 - Backtracking

public List<List<Integer>> kSum(int[] nums, int target, int k) {
	len = nums.length;
	Arrays.sort(nums);
	return kSum(nums, target, k, 0);
}
private List<List<Integer>> kSum(int[] nums, int target, int k, int index) {
	List<List<Integer>> res = new ArrayList<>();
	if(index >= len) {
		return res;
	}
	if(k == 2) {
		int i = index, j = len - 1;
		while(i < j) {
			//find a pair
			if(target - nums[i] == nums[j]) {
				List<Integer> temp = new ArrayList<>();
				temp.add(nums[i]);
				temp.add(target-nums[i]);
				res.add(temp);
				//skip duplication
				while(i<j && nums[i]==nums[i+1]) i++;
				while(i<j && nums[j-1]==nums[j]) j--;
				i++;
				j--;
			//move left bound
			} else if (target - nums[i] > nums[j]) {
				i++;
			//move right bound
			} else {
				j--;
			}
		}
	} else{
		for (int i = index; i < len - k + 1; i++) {
			//use current number to reduce ksum into k-1sum
			List<List<Integer>> temp = kSum(nums, target - nums[i], k-1, i+1);
			if(temp != null){
				//add previous results
				for (List<Integer> t : temp) {
					t.add(0, nums[i]);
				}
				res.addAll(temp);
			}
			while (i < len-1 && nums[i] == nums[i+1]) {
				//skip duplicated numbers
				i++;
			}
		}
	}
	return res;
}

Complexity

  • ⏰ Time complexity: O(n^(k-1))
  • 🧺 Space complexity: O(1)