Leetcode–Combinations

The Problem:

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

Notes:

  1. In each iteration, choose one number larger than the tail element , and append to the list.

Java Solution

public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(k==0) return result;
        for(int i = 1; i <= n-k+1; i++){
            List<Integer> list = new ArrayList<Integer>();
            list.add(i);
            result.add(list);
        }
        k--;
        while(k>0){
            List<List<Integer>> temp = new ArrayList<List<Integer>>();
            for(List<Integer> onelist : result){
                int last = onelist.get(onelist.size()-1);
                for(int j = last+1; j<=n; j++){
                    List<Integer> newone = new ArrayList<Integer>(onelist);
                    newone.add(j);
                    temp.add(newone);
                }
            }
            result = temp;
            k--;
        }
        return result;
    }
}
Advertisements

One thought on “Leetcode–Combinations

  1. Pingback: Leetcode–Letter Combinations of a Phone Number | Linchi is coding

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