码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode]k Sum II

时间:2015-03-04 12:58:47      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:k-sum-ii   lintcode   

题目

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, [1,4] and [2,3] are possible solutions.

Tags Expand
LintCode Copyright Depth First Search

解题思路

和K Sum题类似,但是K Sum只能求到结果个数,但是无法获取历史路径,所以只能使用K Sum的思路一,深度搜索算法

代码

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>> list = new ArrayList<ArrayList<Integer>>();
        if (A.length < k || k <= 0)
            return list;

        for (int i = 0; i < A.length; i++) {
            if (k == 1) {
                if (A[i] == target) {
                    ArrayList<Integer> l = new ArrayList<Integer>();
                    l.add(A[i]);
                    list.add(l);
                    return list;
                }
            } else {
                int[] B = new int[A.length - i - 1];
                System.arraycopy(A, i + 1, B, 0, A.length - i - 1);
                ArrayList<ArrayList<Integer>> sublist = kSumII(B, k - 1, target - A[i]);
                for (ArrayList<Integer> l : sublist) {
                    l.add(0, A[i]);
                    list.add(l);
                }
            }
        }
        return list;
    }
}

[LintCode]k Sum II

标签:k-sum-ii   lintcode   

原文地址:http://blog.csdn.net/wankunde/article/details/44058403

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!