Backtrack的典型,为了更好的back,给原数组SORT一下会比较好,加一个数超过TARGET可以直接剪枝了。
public class Solution {
public List<List<Integer>> combinationSum(int[] nums, int target)
{
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums.length == 0) return res;
Arrays.sort(nums);
helper(res,nums,new ArrayList<Integer>(),target,0);
return res;
}
public void helper(List<List<Integer>> res, int[] nums, List<Integer> tempList, int target, int m)
{
if(target == 0) res.add(tempList);
else if(target < 0) return;
else
{
for(int i = m; i < nums.length; i++)
{
if(target - nums[i] < 0) break;
tempList.add(nums[i]);
helper(res,nums,new ArrayList<Integer>(tempList),target - nums[i],i);
tempList.remove(tempList.size()-1);
}
}
}
}
-----
三刷。
基本一回事,排序一下可以提前剪枝,既然没有负数。有负数就不能一个数无限次的用了。。
Time: O(n^k) n是多少个元素,K是target。这个题不会算,感觉还是指数级别,但是实际上跟具体数据有关,target(k)不停地减少,能用的元素也原来越少,总之不会算。。。
Space: O(n)
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (candidates.length == 0) return res;
Arrays.sort(candidates);
dfs(res, candidates, target, 0, new ArrayList<>());
return res;
}
public void dfs(List<List<Integer>> res, int[] nums, int target, int m, List<Integer> tempList) {
if (target == 0) {
res.add(tempList);
return;
} else {
for (int i = m; i < nums.length; i++) {
if (target - nums[i] < 0) break;
if (i != m && nums[i] == nums[i-1]) continue;
tempList.add(nums[i]);
dfs(res, nums, target - nums[i], i, new ArrayList<>(tempList));
tempList.remove(tempList.size() - 1);
}
return;
}
}
}