216. Combination Sum III
来源:互联网 发布:高中数学知乎 编辑:程序博客网 时间:2024/06/05 06:24
不用多想,直接使用DFS解决
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]]
class Solution { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> result = new ArrayList<>(); if (k > n) { return result; } int[] nums = new int[9]; for (int i = 0; i < 9; i++) { nums[i] = i + 1; } dfs(nums, 0, n, k, new ArrayList<Integer>(), result); return result; } private void dfs(int[] nums, int start, int retarget, int limit, List<Integer> path, List<List<Integer>> result) { if (retarget < 0 || path.size() > limit) { return; } if (retarget == 0 && path.size() == limit) { result.add(new ArrayList<Integer>(path)); return; } for (int i = start; i < nums.length; i++) { path.add(nums[i]); dfs(nums, i + 1, retarget - nums[i], limit, path, result); path.remove(path.size() - 1); } }}
阅读全文
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
- Java中使用Apache POI使用解析excel文件
- poj 2406 Power Strings
- 任意输入一个年份,判断它是否是闰年。
- 中国剩余定理(详解)
- 习题5 5.3
- 216. Combination Sum III
- LeetCode18. 4Sum
- python3单行定义多个变量或赋值
- Installation guide for Kong custom plugins
- 鼠标移入和移出事件mouseenter VS mouseover 、mouseleave VS mouseout
- Eclipse上Maven环境配置使用 (全)
- 【Linux】之 从源代码安装软件(HelloWorld)
- HttpClient连接SSL
- 护肤小常识