Combination Sum
Solution 1
啊哈又是一个DFS,还是N皇后的思路,只是状态上不是每一步只能用一次而是无限次。因此再状态切换上的两个状态为:
- 选择当前位置,下一次递归搜索只要target值还够,就继续考察当前位置
- 不选择当前位置,搜索下一个位置,上一种情况在target值不够的情况下会自动归约到这个状态
此外优化方面再加一个剪枝,先排序一下整个数组,如果当前索引位置的值已经不够target,后面就都不用搜索了。
- O ( n ⋅ 2 n ) O(n \cdot 2^n) O(n⋅2n),初步算的是这个,官方题解给出的那个更紧的上界我不是很懂
- O ( n ⋅ t a r g e t ) O(n \cdot target) O(n⋅target),递归占用最坏是下到target层(target个1相加),所有数字最坏保存n个target长的数组结果(官网算的更紧,但是好像只考虑了递归调用?)
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> tmp;
sort(candidates.begin(), candidates.end());
this->dfs(candidates, target, ans, tmp, 0);
return ans;
}
private:
void dfs(vector<int> & candidates, int target, vector<vector<int>> & ans, vector<int> & tmp, int index) {
if (index >= candidates.size()) {
return;
}
if (target == 0) {
ans.push_back(tmp);
return;
}
if (target - candidates[index] >= 0) {
// 选择当前索引位置
tmp.push_back(candidates[index]);
// 这里不增加,因为可以无限次用当前位置
this->dfs(candidates, target - candidates[index], ans, tmp, index);
tmp.pop_back();
// 跳过当前位置,向下一个位置搜索
this->dfs(candidates, target, ans, tmp, index + 1);
}
}
};
Solution 2
Solution 1的Python实现,注意Python函数调用的引用传值特性
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans = list()
tmp = list()
candidates = sorted(candidates)
self.__dfs(candidates, target, ans, tmp, 0)
return ans
def __dfs(self, candidates: List[int], target: int, ans: List[List[int]], tmp: List[int], index: int) -> None:
# print(ans, target, tmp, index)
if index >= len(candidates): return
if target == 0:
ans.append(deepcopy(tmp))
# print(ans)
return
if target - candidates[index] >= 0:
tmp.append(candidates[index])
self.__dfs(candidates, target - candidates[index], ans, tmp, index)
tmp.pop()
self.__dfs(candidates, target, ans, tmp, index + 1)