LeetCode - 216. Combination Sum III - 思路详解 - C++
2017-01-13 21:06
465 查看
题目
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.翻译
找出所有可能组合,即使用k个数,相加结果为n。假设数值从1到9,在每个组合中,尽可被使用一次。即组成的组合,数据相互不同。思路
这是一道典型的组合问题。首先联想到回溯法;需要处理两个问题。1,判断k个数之和是否是目标值。2,递归求解。
代码
class Solution { public: vector<vector<int>> res; vector<int> ans; int sum; vector<vector<int>> combinationSum3(int k, int n) { if(k == 0 || n == 0 ){ return res; } if(k > n){ return res; } //开始位置,已经用了几个数,当下几个数的和,k为元素个数 dfs(1,0,n,k); return res; } //深度优先搜索 void dfs(int start, int num, int n , int k){ if(num == k){ if(sum == n){ res.push_back(ans); } return; } for(int i = start; i <= 9; i ++ ){ sum += i; ans.push_back(i); if(sum <= n){ dfs(++start,num+1,n,k); } ans.pop_back(); sum -= i; } } };
相关文章推荐
- LeetCode - 217. Contains Duplicate - 思路详解 - C++
- C语言 · 9-1九宫格
- 简易版C++顺序表
- LeetCode-219. Contains Duplicate II-思路详解-C++
- C++ 反向迭代器注意事项
- LeetCode - 228. Summary Ranges - 思路详解- C++
- 康威生命游戏C语言实现(串行+intrinsics并行)
- LeetCode- 169. Majority Element - 思路详解 -C++
- 技能学习经验与C语言学习调查
- LeetCode- 238. Product of Array Except Self - 思路详解 -C++
- C++一些初步知识
- C++中引用(&)的用法和应用实例
- 设计模式之23 - 访问者模式Visitor
- 设计模式之22 - 模板方法Template method
- 设计模式之21 - 策略模式Strategy
- 设计模式之20 - 状态模式State
- 设计模式之19 - 观察者模式Observer
- 设计模式之18 - 备忘录模式Memento
- 设计模式之17 - 中介者模式Mediator
- 设计模式之16 - 迭代器模式Itertor