Combinations

1. Title

Combinations

2. Http address

https://leetcode.com/problems/combinations/

3. The question

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

4. My code(AC)

 1 // Accepted
 2        public List<List<Integer>> combine(int n, int k) {
 3            List<List<Integer>>  result = new ArrayList<List<Integer>>();
 4            List<Integer> subList = null;
 5            for(int begin = 1;  begin <= n; begin++)
 6            {
 7                subList = new ArrayList<Integer>();
 8                subList.add(begin);
 9                getCombinations(begin + 1, n, k, subList, result);
10            }
11           return result;
12         }
13        
14        public void getCombinations(int begin, int end, int k, List<Integer> subResult, List<List<Integer>> result)
15        {
16            
17            if( subResult.size() == k)
18            {
19                 result.add(new ArrayList<Integer>(subResult));
20                return;
21            }
22            for(int i = begin ; i <= end ; i++)
23            {
24                subResult.add(i);
25                getCombinations(i + 1, end, k , subResult, result);
26                subResult.remove(subResult.size() - 1);
27            }
28        }
原文地址:https://www.cnblogs.com/ordili/p/4969961.html