当前位置: 代码迷 >> 综合 >> leetcode-77 Combinations
  详细解决方案

leetcode-77 Combinations

热度:66   发布时间:2023-12-16 05:35:10.0

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

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