LeetCode Combination Sum III

LeetCode Combination Sum III

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]]

Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.


从1~9中取k个数,使得这k个数的和等于n,求出所有取数方案。

简单的递归题,为了不重复,每次从上次取数的下一个取,代码如下:

class Solution {
private:
	void dfs(vector<vector<int>>& ans, vector<int>& cand, int step, const int& k,int sum) {
		if (cand.size() == k&&sum == 0) {
			ans.push_back(cand);
			return;
		}
		for (int i = step; i <= 9; ++i) {
			if (i > sum)break;
			cand.push_back(i);
			dfs(ans, cand, i + 1, k, sum - i);
			cand.pop_back();
		}
	}
public:
	vector<vector<int>> combinationSum3(int k, int n) {
		vector<vector<int>> ans;
		vector<int> cand;
		dfs(ans, cand, 1, k, n);
		return ans;
	}
};

本代码提交AC,用时3MS。

Leave a Reply

Your email address will not be published. Required fields are marked *