1.這一題也是回溯的問題,使用了遞歸的方式來實現(xiàn)回溯禾怠。
ps:leetcode上的題目盡量不要定義全局變量返奉,不然就會向我今天一樣。
????運(yùn)行的時候是正確的吗氏,但是提交的時候就錯誤了芽偏。
class Solution {
? ? public List<List<Integer>> combinationSum(int[] candidates, int target) {
? ? ? ? List<List<Integer>> list=new ArrayList<List<Integer>>();
? ? ? ? backTracking(list,candidates,target,new ArrayList<Integer>(),0,0);
? ? ? ? return list;
? ? }
? ? public? void backTracking(List<List<Integer>> list,int[] candidates,int target,ArrayList<Integer> b,int sum,int count){
? ? ? ? if(sum==target){
? ? ? ? ? ? list.add(b);
? ? ? ? }else if(sum<target){
? ? ? ? ? ? for(int i=count;i<candidates.length;i++){
? ? ? ? ? ? ? ? ArrayList<Integer> c=new ArrayList<Integer>(b);
? ? ? ? ? ? ? ? c.add(candidates[i]);
? ? ? ? ? ? ? ? backTracking(list,candidates,target,c,sum+candidates[i],i);
? ? ? ? ? ? }
? ? ? ? }
? ? }
}