216. 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.

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

链接: http://leetcode.com/problems/combination-sum-iii/

7/16/2017

这道题目没说清楚,每个combination当中不能有重复的值。

注意,第18行可以改为for (int i = pos; i <= 9; i++)并把pos当作递归的一个值,这样每一步可以减少很多比较

 1 public class Solution {
 2     public List<List<Integer>> combinationSum3(int k, int n) {
 3         List<List<Integer>> result = new ArrayList<>();
 4         if (n / k > 9 || n / k < 1) {
 5             return result;
 6         }
 7         List<Integer> combination = new ArrayList<>();
 8         combinationSum(result, k, n, combination);
 9         return result;
10     }
11     
12     private void combinationSum(List<List<Integer>> result, int k, int n, List<Integer> combination) {
13         if (k == 0 && n == 0) {
14             result.add(new ArrayList<>(combination));
15             return;
16         }
17         if (n < 0 || k < 0) return;
18         for (int i = 1; i <= 9; i++) {
19             if (combination.size() > 0 && i <= combination.get(combination.size() - 1)) continue;
20             combination.add(i);
21             combinationSum(result, k - 1, n - i, combination);
22             combination.remove(combination.size() - 1);
23         }
24     }
25 }

别人的答案

http://www.cnblogs.com/yrbbest/p/4982868.html

更多讨论

https://discuss.leetcode.com/category/224/combination-sum-iii

posted @ 2017-07-17 11:12  panini  阅读(262)  评论(0编辑  收藏  举报