心得:尽量把不符合的条件过滤,然后进行回溯,以前用的是每次递归
都new一个链表,其实应该把一个链表传进去进行回溯。
代码:
class Solution { public List
> combinationSum(int[] candidates, int target) { LinkedList
> list=new LinkedList<>(); if(candidates==null||candidates.length==0) return list; Arrays.sort(candidates); rec(0,list,new LinkedList (),candidates,target); return list; } public void rec(int index,LinkedList
> list,LinkedList tmp,int[] candidates,int target) { for(int i=index;i 0) { tmp.add(candidates[i]); rec(i,list,tmp,candidates,target-candidates[i]); tmp.removeLast(); } else { tmp.add(candidates[i]); LinkedList b=new LinkedList<>(tmp); tmp.removeLast(); list.add(b); } } }}