Combination Sum

Descirption:

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.

Note:

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

 

For example, given candidate set [2, 3, 6, 7] and target 7
A solution set is: 

[
  [7],
  [2, 2, 3]
]


Thoughts:
要解决这个问题要使用回溯的思想。所谓的回溯就是对所有的解进行枚举,能够走通的就继续走,否则就回退一步,尝试另一条路径,直到所有的路径都进行了遍历。
对于当前的回溯点我们需要直到当前所有可能的路径,然后朝着所有可能的路径继续前进,对于不可能的路径直接跳过

以下是java代码package middle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CombinationSum {
    
    public List<List<Integer>> combinationSum(int[] candidates, int target){
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        Arrays.sort(candidates);
        backtrack(list, new ArrayList(),candidates,  target, 0);
    /*    System.out.println(list);*/
        return list;
    }
    
    private void backtrack(List<List<Integer>> list, ArrayList arrayList,
            int[] candidates, int target, int start) {
        // TODO Auto-generated method stub
        if(target < 0){
            return;
        }else if(target == 0){

      //we should new an ArrayList, because the arrayList will change later,
      //if we do not copy it's value, list will add []

            list.add(new ArrayList<Integer>(arrayList));
        }else{
            for(int i = start;i<candidates.length;i++){
                arrayList.add(candidates[i]);
                backtrack(list, arrayList, candidates, target-candidates[i], i);
                arrayList.remove(arrayList.size() - 1);
            }
        }
    }
    
    public static void main(String[] args){
        CombinationSum sum = new CombinationSum();
        int[] candidates = new int[]{2, 3,5 ,7};
        sum.combinationSum(candidates, 7);
    }
}

 



posted @ 2017-09-09 09:09  whatyouknow123  阅读(123)  评论(0编辑  收藏  举报