Combinations, Leetcode 解题笔记

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:


依然是DFS题,注意题目要求不同决定了base case和递归规律的不同,做这种题目前还是不能得心应手,总是有出错的地方,需要再系统地学习。

public class Solution {
    public ArrayList<ArrayList<Integer>> combine(int n, int k) {
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> sol = new ArrayList<Integer>();
        dfs(ret, sol, n, k, 0);
        return ret;
    public void dfs(ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> sol, int n, int k, int index){
        if(sol.size() == k){
            ret.add(new ArrayList<Integer>(sol));
        for(int i = index; i < n; i++){
            dfs(ret, sol, n, k, i + 1);

Leave a Reply

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

You are commenting using your 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