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);
            }
        }
    

      

  • 相关阅读:
    ffmpeg文档03-详细说明
    ffmpeg文档01-命令语法
    ffmpeg文档02-描述/概览
    OpenWrt使用花生壳脚本
    upc 9315 Philosopher’s Walk
    upc 9312 Game Map
    hdu 1251 统计难题
    Trie树简要讲解
    [算法]一次商品交易利益最大化
    [c语言]左移和右移
  • 原文地址:https://www.cnblogs.com/apanda009/p/7294274.html
Copyright © 2011-2022 走看看