Sunday, May 3, 2015

[LeetCode] Combinations

Combinations

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],
]
Solution: Note that combine(n, k) is the union of the following two, depending on whether n is used:
1. combine(n - 1, k).
2. combine(n - 1, k - 1), plus the element n.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        ArrayList<List<Integer>> list = new ArrayList<List<Integer>>();
        if (n < k || k == 0) {
            return list;
        }
        if (k == 1) {
            for (int i = 1; i <= n; i++) {
                ArrayList<Integer> l = new ArrayList<Integer>();
                l.add(i);
                list.add(l);
            }
            return list;
        }
        list.addAll(combine(n - 1, k));
        List<List<Integer>> li = combine(n - 1, k - 1);
        for (List<Integer> ll : li) {
            ArrayList<Integer> l = new ArrayList<Integer>(ll);
            l.add(n);
            list.add(l);
        }
        return list;
    }
}

No comments:

Post a Comment