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
. Return:
[
[1,4],
[2,3]
]
分析:递归
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) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
helper(A, k, target, 0, res, new ArrayList<Integer>());
return res;
}
void helper(int[] A, int k, int target, int index, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> list) {
if(target == 0 && k == 0) {
res.add(new ArrayList<Integer>(list));
return;
}
if(index >= A.length || target < 0 || k < 0) return;
for(int i = index; i < A.length; i++) {
list.add(A[i]);
helper(A, k - 1, target - A[i], i + 1, res, list);
list.remove(list.size() - 1);
}
}
}