Loading

LeetCode 77 组合

LeetCode77 组合

题目描述

给定两个整数 nk,返回 1 ... n 中所有可能的 k 个数的组合。

样例

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

算法分析

  • 枚举位置、加上顺序条件,保证唯一

时间复杂度

Java代码

class Solution {
    static List<List<Integer>> ans = new ArrayList<List<Integer>>();
    static List<Integer> t = new ArrayList<Integer>();
    static void dfs(int n, int k, int u, int start){
        if(u == k){
            ans.add(new ArrayList<Integer>(t));
            return;
        }
        for(int i = start; i <= n; i ++){
            t.add(i);
            dfs(n,k,u+1,i+1);
            t.remove(t.size()-1);
        }
    }
    public List<List<Integer>> combine(int n, int k) {
        ans.clear();
        dfs(n,k,0,1);
        return ans;
    }
}

posted @ 2020-11-18 14:13  想用包子换论文  阅读(86)  评论(0)    收藏  举报