Lintcode: k Sum II

时间:2022-04-24 12:06:02
Given n unique integers, number k (1<=k<=n)  and target. Find all possible k integers where their sum is target.

Example
Given [1,2,3,4], k=2, target=5, [1,4] and [2,3] are possible solutions.

这道题同Combination Sum II

 public class Solution {
/**
* @param A: an integer array.
* @param k: a positive integer (k <= length(A))
* @param target: a integer
* @return a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> kSumII(int A[], int k, int target) {
// write your code here
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> path = new ArrayList<Integer>();
helper(res, path, A, k, target, 0);
return res;
} public void helper(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> path, int[] A, int k, int remain, int index) {
if (path.size() == k) {
if (remain == 0) {
res.add(new ArrayList<Integer>(path));
}
return;
}
for (int i=index; i<A.length; i++) {
path.add(A[i]);
helper(res, path, A, k, remain-A[i], i+1);
path.remove(path.size()-1);
}
}
}