time: O(2^n), candidate choose or not choose, n times
space: O(target)
classSolution {publicList<List<Integer>> combinationSum(int[] candidates,int target) {List<List<Integer>> res =newArrayList<>();helper(res,newArrayList<>(), candidates, target,0);return res; }privatevoidhelper(List<List<Integer>> res,List<Integer> list,int[] candidates,int target,int start) {if (target <0) {return; } elseif (target ==0) {res.add(newArrayList<>(list)); } else {for (int i = start; i <candidates.length; i++) {list.add(candidates[i]);helper(res, list, candidates, target - candidates[i], i); // pass i, why i = start => for seq searchlist.remove(list.size()-1); } } }}/*7 - any of [],7 = [2,3,6,7]7 - 2 = 55 - 2 = 33 - 2 => no, 3 - 3 ok! backtrack*/
why we cant just use for (i = 0..., because it should pass "the current index
and pass i, means we can reuse the same number
backtracking, we always have a tree (ex: [2, 3, 6, 7]), then cut and find the ans.
[2, 3, 6, 7]
classSolution {publicList<List<Integer>> combinationSum(int[] candidates,int target) {List<List<Integer>> result =newArrayList<>();dfs(result, candidates, target,newArrayList<>(),0);return result; }privatevoiddfs(List<List<Integer>> result,int[] candidates,int target,List<Integer> list,int start) {if (target <0) {return; }if (target ==0) {result.add(newArrayList<>(list));return; }// if every time from i = 0, will generate like [2,2,3] [2,3,2], [3,2,2]// just use order seq to pass the i indexfor (int i = start; i <candidates.length; i++) {list.add(candidates[i]);dfs(result, candidates, target - candidates[i], list, i);list.remove(list.size()-1); } }}
ๆณ่ฆ้ฟๅ ้็จฎ็ๆณ, ่จๅพ use i = start, ไธฆไธๅณๅ ฅ i, ้ๆจฃๅฏไปฅไฟ่ญๅณๅ ฅ i ็้ ๅบๆฏๅฐ็, ๅฐฑไธๆๆ้่คๅ้ก