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],
]
public class Solution {
    //There are 2 situations: 
    //(1)number n is selected -> C(n-1, k-1)
    //(2)number n is not selected -> C(n-1, k)
    //Therefore, C(n, k) = C(n-1, k-1) + C(n-1, k)
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new LinkedList<>(); 
        if (n == k || k == 0) {
            List<Integer> row = new LinkedList<>(); 
            for (int i = 1; i <= k; i++) {
                row.add(i);
            }
            result.add(row);
            return result; 
        }
        
        result = this.combine(n-1, k-1);
        result.forEach(e -> e.add(n));      //forEach
        result.addAll(this.combine(n-1, k));//addAll 
        return result; 
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s