216. Combination Sum III
来源:互联网 发布:中国大学生失业率数据 编辑:程序博客网 时间:2024/06/05 17:47
题目
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]]
解答
博主对回溯算法不熟,参照了别人做法。
void res(int k, int n, int level, vector<int> &temp, vector<vector<int> > &result) { cout << "["; for (auto t : temp) cout << t << " "; cout << "]" << endl; if (n < 0) return; if (n == 0 && temp.size() == k) result.push_back(temp); for (int i = level; i <= 9; ++i) { temp.push_back(i); res(k, n - i, i + 1, temp, result); temp.pop_back(); }}vector<vector<int> > combinationSum3(int k, int n) { vector<vector<int> > result; vector<int> temp; res(k, n, 1, temp, result); return result;}
ps:应该好好学学算法,加油!
0 0
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- 216. Combination Sum III
- android中的键值对
- 终端命令
- android.content.ActivityNotFoundException: No Activity found to handle Intent
- CUDA总结:线程网络和线程分配
- 怎么编写makefile
- 216. Combination Sum III
- 数据结构期末总结
- Mysql日期类型
- 二:Hibernate映射机制
- Android开发中这些小技巧你都知道吗?(一)
- oracle linux 7 安装oracle 12c
- Android四大组件—Service
- 虚拟机系统安装详细步骤(图文)
- 安装windows10中出现的问题