Combination Sum III

1. Title

Combination Sum III

2. Http address

https://leetcode.com/problems/combination-sum-iii/

3. The question

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

4. My code(AC)

 1     // Accepted
 2       public List<List<Integer>> combinationSum3(int k, int n) {
 3             
 4           List<List<Integer>> result = new ArrayList<List<Integer>>();
 5           getNumber(1, k , n, new ArrayList<Integer>(), result);
 6           return result;
 7         }
 8       
 9       public void getNumber(int begin, int k , int n, ArrayList<Integer> subList, List<List<Integer>> result)
10       {
11         int len = subList.size();
12         int sum = 0;
13         if( len == k )
14         {
15             for(int i = 0 ; i < len ; i++)
16             {
17                 sum += subList.get(i);
18             }
19             if( sum == n)
20             {
21                 result.add(new ArrayList<Integer>(subList));
22             }
23             return;
24         }
25         
26         for(int i = begin ; i <= 9 ; i++)
27         {
28             subList.add(i);
29             getNumber(i + 1, k, n, subList, result);
30             subList.remove(subList.size() - 1);
31         }
32       }

 

posted @ 2015-11-16 20:40  ordi  阅读(118)  评论(0编辑  收藏  举报