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<List<Integer>> combinationSum(int[] candidates, int target) {
    bubbleSort(candidates);
    List<List<Integer>> arrayLists = new ArrayList<List<Integer>>();
    if (candidates==null||candidates.length==0||target<0) {
        return arrayLists;
    }
    List<Integer> arrayList = new ArrayList<Integer>();
    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<List<Integer>> arrayLists,List<Integer> 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<Integer>(arrayList));
        
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given a collection of candidate numbers (C) and a target ...
    敲一手烂代码阅读 193评论 0 0
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,129评论 0 23
  • 百日阅读第 12 天《随园食单》 清 袁枚 在袁枚《随园食单》中对鹅的食谱描写不多,只有烧鹅、云林鹅两种制法。 因...
    木子罗阅读 958评论 2 13
  • 奶奶,今天是您的搬迁之喜,想着您从此可以住上亮堂的家,我们都很高兴,爸爸说您住得安稳舒适了,他也可以了却了一桩心事...
    婉慧阅读 760评论 3 3