LeetCode 77. Combinations(递归)

题目来源:https://leetcode.com/problems/combinations/

问题描述

77. Combinations

Medium

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2

Output:

[

  [2,4],

  [3,4],

  [2,3],

  [1,2],

  [1,3],

  [1,4],

]

------------------------------------------------------------

题意

求n个数字中所有的k个数字的组合。

------------------------------------------------------------

思路

递归。dfs的参数有3个(l, r, k),意义是在[l, r]的范围内取k个数的组合,返回表示这样的组合的List>.

------------------------------------------------------------

代码

class Solution {
    public List> combine(int n, int k) {
        if (n == 0 || k == 0)
        {
            return Collections.emptyList();
        }
        return dfs(1, n, k);
    }
    
    private List> dfs(int l, int r, int k) {
        List> ans = new LinkedList<>();
        if (k == r-l+1)
        {
            List tmp = new LinkedList();
            for (int i=l; i<=r; i++)
            {
                tmp.add(i);
            }
            ans.add(tmp);
        }
        else if (k == 1)
        {
            for (int i=l; i<=r; i++)
            {
                List tmp = new LinkedList();
                tmp.add(i);
                ans.add(tmp);
            }
        }
        else
        {
            for (int i=l; i<=r-k+1; i++)
            {
                List> pre = dfs(i+1, r, k-1);
                for (List tmp: pre)
                {
                    tmp.add(i);
                    ans.add(tmp);
                }
            }
        }
        return ans;
    }
}

 

你可能感兴趣的:(LeetCode)