Array:Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.

public static List> combinationSum(int[] candidates, int target) {
    bubbleSort(candidates);
    List> arrayLists = new ArrayList>();
    if (candidates==null||candidates.length==0||target<0) {
        return arrayLists;
    }
    List arrayList = new ArrayList();
    getRes(arrayLists, arrayList, candidates, target, 0);
    
    return arrayLists;
}

public static void bubbleSort(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr.length-1-i; j++) {
            if (arr[j]>arr[j+1]) {
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}

private static void getRes(List> arrayLists,List arrayList,int[] arr,int target,int index) {

    if (target > 0) {
        for (int i = index; i < arr.length ; i++) {
            arrayList.add(arr[i]);
            getRes(arrayLists, arrayList, arr, target - arr[i], i);
            arrayList.remove(arrayList.size() - 1);
        }
    } else if (target == 0) {
        arrayLists.add(new ArrayList(arrayList));
        
    }
}

你可能感兴趣的:(Array:Combination Sum)