首页 > 代码库 > k Sum II
k Sum II
Given n unique integers, number k (1<=k<=n) and target. Find all possible k integers where their sum is target. Have you met this question in a real interview? Yes Example Given [1,2,3,4], k = 2, target = 5. Return: [ [1,4], [2,3] ] Tags LintCode Copyright Depth First Search
public ArrayList<ArrayList<Integer>> kSumII(int[] A, int k, int target) { // write your code here ArrayList<ArrayList<Integer>> ans = new ArrayList<>(); ArrayList<Integer> list = new ArrayList<>(); if (A == null || k > A.length) { ans.add(list); return ans; } Arrays.sort(A); dfs(ans, list, A, k, target, 0); return ans; } private void dfs(ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> list, int[] A, int k, int target, int pos) { if (k == 0 && target == 0) { ans.add(new ArrayList(list)); return; } if (target < 0 || pos >= A.length || pos + k > A.length) { return; } for (int i = pos; i < A.length; i++) { list.add(A[i]); dfs(ans, list, A, k - 1, target - A[i], i + 1); list.remove(list.size() - 1); } }
k Sum II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。