LeetCode77. Combinations(组合)JAVA实现

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,返回 1 ... 中所有可能的 k 个数的组合。

示例:

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

思路:使用dfs直接求解。

实现代码:

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> tmp = new ArrayList<Integer>();
        dfs(res,tmp,n,k,1);
        return res;
    }
    public void dfs(List<List<Integer>> res, List<Integer> tmp, int n, int k, int m){
        if(k==0){
            res.add(new ArrayList<Integer>(tmp));
            return;
        }
        for(int i=m;i<=n;i++){
            tmp.add(i);
            dfs(res, tmp, n, k-1, i+1);
            tmp.remove(tmp.size()-1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_25406563/article/details/84397194