码迷,mamicode.com
首页 > 其他好文 > 详细

Combination Sum

时间:2017-09-09 10:46:06      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:直接   where   arrays   ret   思想   lis   turn   i++   generated   

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);
    }
}

 



Combination Sum

标签:直接   where   arrays   ret   思想   lis   turn   i++   generated   

原文地址:http://www.cnblogs.com/whatyouknow123/p/7497155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!