代码随想录算法训练营day24 | 77. 组合

121 阅读1分钟

77.组合

给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。 你可以按 任何顺序 返回答案。

77. 组合 - 力扣(Leetcode)

思路

使用res存储组合结果,使用combination存储当前组合。

  • combination.size() == k时,找到一个符合条件的组合,将结果保存到res中。注意,保存结果时要新建一个List,与之前的combination要隔离开,属于深拷贝,避免之后combination的变化影响res中已保存的结果。
  • 否则,从start的位置开始向后遍历,范围为[start, n],枚举取每一个值的结果,并在取值 i 后,继续遍历,从[i, n]中继续取值,直到combination中有k个值为值。
  • 每种取值方法遍历结果,要将刚刚取的值移除出来,避免对后续结果产生影响。

代码

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> combination = new ArrayList<>();
        traversal(res,combination,n,k,1);
        return res;
    }

    private void traversal(List<List<Integer>> res,List<Integer> combination, int n, int k, int start){

        if(combination.size() == k){
            res.add(new ArrayList<Integer>(combination));
            return;
        }

        for(int i = start; i <= n; i++){
            combination.add(i);
            traversal(res,combination,n,k,i + 1);
            combination.remove(combination.size() - 1);
        }

    }
}