TODO:
1, 分析前几次的代码,抓bug 分析理解错误。
2, 描述过程,知道过程才会在 当题目有所变化的时候 知道在那行代码加什么东西,所以啊!!写程序程序,本质就是过程,programming 就是一个流程的设计。
3, 这一类就叫做backtracking,backtracking,有2个特点:1,添加元素是最后的动作,记得是make a copy,而不是本身,谨记java里都passing by reference;2,既然是回溯那就是有add 有 remove,在list的remove()中,变量是index,而不是具体的某个值。这样也是出于安全和速度的考虑,安全就是这个值可能没有,速度的话就是不需要再搜索一遍了,直接用index 查找就可以。
回溯虽然慢,但也没看到其他解法,因为是NP 问题,所以也就肯定不是Polynomial time能完成的,都是指数时间复杂度。
第一次各种bug的代码
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> list= new ArrayList<>();
if(candidates==null || candidates.length==0) return list;
// forget to sort Arrays.sort(candidates);
List<Integer> item = new ArrayList<>();
generator(list, item, 0, candidates, target);
return list;
}
private void generator(List<List<Integer>> list, List<Integer> item, int start, int[] candidates, int target){
if(target<0) return;
if(target==0){
list.add(item); // bug: should make a copy of item, not item itself. Java is all passing by reference
return;
}
for(int i=start; i<candidates.length; i++){
item.add(candidates[i]);
generator(list, item, start, candidates, target-candidates[i]); // bug: start should be i
item.remove(candidates[i]); //
}
}
}
one-time bug-free 的代码, 8'52''
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> list= new ArrayList<>();
if(candidates==null || candidates.length==0) return list;
Arrays.sort(candidates);
List<Integer> item = new ArrayList<>();
generator(list, item, 0, candidates, target);
return list;
}
private void generator(List<List<Integer>> list, List<Integer> item, int start, int[] candidates, int target){
if(target<0) return;
if(target==0){
list.add(new ArrayList<Integer>(item));
return;
}
for(int i=start; i<candidates.length; i++){
//if(i!=0 && candidates[i]==candidates[i-1]) continue;
item.add(candidates[i]);
generator(list, item, i, candidates, target-candidates[i]);
item.remove(item.size()-1);
}
}
}