【LeetCode算法练习(C++)】Combination Sum
程序员文章站
2022-05-21 22:38:49
...
题目:
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]
链接:Combination Sum
解法:先对数组排序,递归遍历,将正确的解添加到返回数组中。时间O(n^2)
class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
vector<vector<int> > ans;
vector<int> out;
sort(candidates.begin(), candidates.end());
combinationSumDFS(candidates, target, 0, out, ans);
return ans;
}
void combinationSumDFS(vector<int> &candidates, int target, int start, vector<int> &out, vector<vector<int> > &res) {
if (target < 0) return;
else if (target == 0) res.push_back(out);
else
for (int i = start; i < candidates.size(); ++i) {
out.push_back(candidates[i]);
combinationSumDFS(candidates, target - candidates[i], i, out, res);
out.pop_back();
}
}
};
Runtime: 13 ms
推荐阅读
-
LeetCode C++ 599. Minimum Index Sum of Two Lists【Hash Table】简单
-
LeetCode C++ 454. 4Sum II【Hash Table/Sort/Two Pointers/Binary Search】
-
leetcode算法练习——不同的二叉搜索树
-
leetcode算法练习——不同的二叉搜索树
-
算法分析与设计丨第一周丨 LeetCode(1)——Two Sum
-
leetcode算法练习【240】搜索二维矩阵 II
-
数据结构线段树介绍与笔试算法题-LeetCode 307. Range Sum Query - Mutable--Java解法
-
程序员进阶之算法练习:LeetCode专场
-
【leetcode】633. Sum of Square Numbers(Python & C++)
-
Leetcode 39. Combination Sum 回溯法