2022-3-29 高频 day3
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
1 class Solution { 2 int sum=0; 3 int t; 4 List<List<Integer>> ans; 5 public List<List<Integer>> combinationSum(int[] candidates, int target) { 6 // dfs 对于每一个数字 有0~target/num种选择 7 ans=new ArrayList<>(); 8 List<Integer> list=new ArrayList<>(); 9 t=target; 10 dfs(candidates,0,list); 11 return ans; 12 } 13 14 public void dfs(int[] candidates,int index,List<Integer> list){ 15 if (sum>=t||index>=candidates.length) { 16 if (sum==t) ans.add(new ArrayList<>(list)); 17 //System.out.print(list); 18 return; 19 } 20 for (int i=0;i<=(t-sum)/candidates[index];i++) { 21 sum+=i*candidates[index]; 22 for (int j=0;j<i;j++) list.add(candidates[index]); 23 //System.out.print(list); 24 dfs(candidates,index+1,list); 25 sum-=i*candidates[index]; 26 for (int j=0;j<i;j++) list.remove(list.size()-1); 27 //System.out.print(list); 28 } 29 } 30 }
思路:dfs搜素。
浙公网安备 33010602011771号