216. Combination Sum III

題目:html

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

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


Example 1:htm

Input: k = 3, n = 7blog

Output: 遞歸

[[1,2,4]]

Example 2:leetcode

Input: k = 3, n = 9rem

Output:get

[[1,2,6], [1,3,5], [2,3,4]]

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

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

相關文章
相關標籤/搜索