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

k Sum II

时间:2016-01-18 08:01:04      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

Given n unique integers, number k

Example

Given [1,2,3,4], k = 2, target = 5. Return:

[
  [1,4],
  [2,3]
]

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 
     */ 

    ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> kSumII(int[] A, int k, int target) {
        // write your code here

        ArrayList<Integer> list=new ArrayList<Integer>();
        
        if(A.length==0 || A==null || k>A.length || k<0) return res;
       
        kSum(A,0,k,target,list);
        
        return res;
        
    }
    
    public void kSum(int[] A,int begin,int k, int target,ArrayList<Integer> preList)
    {

        if (k == 0)
        {
            if (target == 0)
                res.add(new ArrayList<Integer>(preList));
            return;
        }
        
        for(int i=begin;i<A.length;i++)
        {
                preList.add(A[i]);
                kSum(A,i+1,k - 1,target-A[i],preList);
                preList.remove(preList.size()-1);
        }
    }
}

 



 

 

 

k Sum II

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/5138222.html

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