組合數組合

1、給定一個無重複元素的數組和一個目標數target,找出數組中全部可使數字和爲target的組合

遞歸回溯法,經過排序來去重。java

數組中的數字能夠無限制重複被選取。數組

說明:spa

  • 全部數字(包括 target)都是正整數。
  • 解集不能包含重複的組合。 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<>();
        Arrays.sort(candidates);
        wuCombinationSumTemp(candidates,target,result,temp,0);
        return result;
    }
    public static void wuCombinationSumTemp(int[] candidates, int target,List<List<Integer>> result, List<Integer> temp,int index) {
        if(target<0) {
            return;
        }
        if(target==0) {
            List<Integer> list = new ArrayList<>(temp);
            result.add(list);
            return;
        }
        int len = candidates.length;
        int tempLen = temp.size();
        for(int i=index;i<len;i++) {
            temp.add(candidates[i]);
            wuCombinationSumTemp(candidates, target-candidates[i],result,temp,i);
            temp.remove(tempLen);
        }
        return;
    }
}

2、給定一個數組和一個目標數target,找出數組中全部可使數字和爲target的組合

數組中的每一個數字在每一個組合中只能使用一次。code

說明:blog

  全部數字(包括目標數)都是正整數。
  解集不能包含重複的組合。 排序

這裏的解題思想主要是動態規劃的思想,而後還有很重要的一點就是這裏的去重的方法。遞歸

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = null;
        result = zuhe(candidates,target,candidates.length);
        return result;
    }
    public static List<List<Integer>> zuhe(int[] candidates, int target,int len) {
        List<List<Integer>> result = new ArrayList<>();
        List<List<Integer>> temp = null;
        if(len == 0){
            if(target==0) {
                List<Integer> list = new ArrayList<Integer>(); 
                result.add(list);
            }
            return result;
        }else{
            if(target<0){
                return result;
            }
            if(target==0){
                List<Integer> list = new ArrayList<Integer>();   
                result.add(list);
                return result;
            }
            int k = 0;
            if(len!=1){
                for(int i=len-2;i>=0;i--){
                    if(candidates[i]!=candidates[len-1]){
                        k = i+1;
                        break;
                    }
                } 
            }
            for(int i=k;i<=len;i++){
                temp = zuhe(candidates, target-candidates[len-1]*(i-k),k);
                for(List<Integer> list:temp){
                    for(int j=k;j<i;j++){
                        list.add(candidates[len-1]);
                    }
                }
                result.addAll(temp);
            }
            return result;
        }
    }
}
相關文章
相關標籤/搜索