http://www.lintcode.com/en/problem/k-sum-ii/
找出所有和爲target且長度爲k的子數組
dfs,當前位置可以選也可以不選
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();
dfs(res, A, k, target, 0, new ArrayList());
return res;
}
private void dfs(ArrayList<ArrayList<Integer>> res, int[] nums, int k, int target, int index, ArrayList<Integer> list) {
if (target == 0 && k == 0) {
res.add(new ArrayList(list));
return;
}
if (k < 0 || index >= nums.length || target < 0) {
return;
}
dfs(res, nums, k, target, index + 1, list);
list.add(nums[index]);
dfs(res, nums, k - 1, target - nums[index], index + 1, list);
list.remove(list.size() - 1);
}
}