1. 程式人生 > >29.Combination Sum(和為sum的組合)

29.Combination Sum(和為sum的組合)

剪枝 pos clas java rep array ret turn mov

Level:

??Medium

題目描述:

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target
    ) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

思路分析:

? 先對數組進行排序,方便後面遞歸回溯的過程中進行剪枝。然後設置一個變量sum,記錄當前序列的數字和,如果sum的值等於target那麽當前序列就是結果的一種,我們利用回溯的思想,找出所有滿足要求得解。

代碼:

public class Solution{
    List<List<Integer>>res=new ArrayList<>();
    public List<List<Integer>>combinationSum(int []candidates,int target){
        if(candidates==null||candidates.length==0)
            return res;
        Arrays.sort(candidates);//排序,方便後面剪枝
        find(candidates,0,0,target,new ArrayList<>());
        return res;
    }
    public void find(int[]candidates,int start,int sum,int target,ArrayList<Integer>list){
        if(sum==target){
            res.add(new ArrayList<Integer>(list));
            return;
        }
        for(int i=start;i<candidates.length;i++){
            if(sum+candidates[i]<=target){
                list.add(candidates[i]);
               find(candidates,i,sum+candidates[i],target,list);
                list.remove(Integer.valueOf(candidates[i]));
            }else{
                break; //剪枝
            }
        }
    }
}

29.Combination Sum(和為sum的組合)