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:

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

依然是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));
            return;
        }
        for(int i = index; i < n; i++){
            sol.add(i+1);
            dfs(ret, sol, n, k, i + 1);
            sol.remove(sol.size()-1);
        }
    } 
}
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