zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    

      

  • 相关阅读:
    对象结构型
    对象结构型
    对象行为型模式
    定时任务(二)
    定时任务(一)
    kill端口-更新sql-添加字段
    获取ip和端口号
    List集合中的末位元素置首位
    首页报表数据展示(一)
    具体的类中包括枚举类写法
  • 原文地址:https://www.cnblogs.com/apanda009/p/7294274.html
Copyright © 2011-2022 走看看