题目
链接:https://leetcode.com/problems/combination-sum-iii/
**Level: ** Medium
Discription:
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Example 1:
Input: k = 3, n = 7
Output: [[1,2,4]]
Note:
- All numbers will be positive integers.
- The solution set must not contain duplicate combinations.
代码1
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> ret;
vector<int> temp;
search(n, k, 1, ret, temp);
return ret;
}
void search(int n, int k, int start, vector<vector<int>> &ret, vector<int> &temp)
{
if(n==0 && k==0)
{
ret.push_back(temp);
return;
}
if(n<0 || k<0 || start==10)
return;
for(int i = start; i <= 9 ; i++)
{
if(i>n)
return;
temp.push_back(i);
search(n-i, k-1, i+1, ret, temp);
temp.pop_back();
}
}
};
思考
- 算法时间复杂度,对这题来说,只有9个数字,取k个数字即可。时间复杂度正比于(C_9^k)。若整数个数任意,时间复杂度就是O(n!)。
- 这题用的递归的思想,递归主要包含递归体和出口,不断地调用自身,在一定条件下返回。不是很熟悉,此外对这种算法的时间复杂度分析比较麻烦,继续刷题加深理解。