LeetCode-Combination Sum III-解题报告

来源:互联网 发布:初音未来mmd动作数据 编辑:程序博客网 时间:2024/05/16 06:58

原题链接https://leetcode.com/problems/combination-sum-iii/

Find all possible combinations of k numbers that add up to a numbern, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.


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

解题思路:使用dfs,从1开始每隔后面符合条件的数字都需要比前一个数字大。当剩余值除以剩下的个数的平均值比下一个小 则返回 ,并且平均值不能大于9.


<span style="font-size:14px;">class Solution {public:vector<int>tmp;vector<vector<int> >ans;int k;vector<vector<int> > combinationSum3(int k, int n) {tmp.resize(k);this->k = k;dfs(1, n, 1);return ans;}void dfs(int s, int n, int deep){if (deep == k){if (n > tmp[k - 2] && n <= 9){tmp[k-1] = n;ans.push_back(tmp);}return;}for (int i = s; i <= 9; ++i){if ((n - i) / (k - deep) >= i + 1 && (n - i) / (k - deep) <= 9){tmp[deep - 1] = i;dfs(i + 1, n - i, deep + 1);}}}};</span>


0 0
原创粉丝点击