leecode 39 Combination Sum

題目詳情

Given a set of candidate numbers (C) (without duplicates) 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.

輸入一個不含重複數字的候選的數字集(C)和一個目標數字(T)。咱們須要找出c中的數字的不一樣組合,使得每一種組合的元素加和爲T。code

For example, 輸入的候選集[2, 3, 6, 7]和目標數字7,
結果集是:
[[7],[2, 2, 3]]遞歸

想法

  • 這道題採起了遞歸的思路。
  • 遞歸方法的輸入參數分別是,最終須要返回的結果list,暫存元素list,候選集,離目標元素和的差值,和開始遍歷的起點。
  • 每次將一個元素加入templist的時候,判斷是否知足templist中的元素加和等於target,若是等於,直接將templist加入最終返回的結果集res。若是加和大於target,那麼就不必繼續遞歸往templist中增長元素了。若是加和小於list,那麼繼續遞歸加入新的元素。

解法

public List<List<Integer>> combinationSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        backtrack(res,new ArrayList<>(),nums,target,0);
        return res;
    }
    public void backtrack(List<List<Integer>> res,List<Integer> temp,int[] nums,int remain,int start){
        if(remain <0)return;
        if(remain == 0)res.add(new ArrayList<>(temp));
        else{
            for(int i=start;i<nums.length;i++){
                temp.add(nums[i]);
                backtrack(res,temp,nums,remain-nums[i],i);
                temp.remove(temp.size()-1);
            }
        }
    }
相關文章
相關標籤/搜索