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); } } }
时间: 2024-10-05 18:51:00