微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

77. Combinations - Medium

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

Example:

Input: n = 4,k = 2
Output:
[
  [2,4],[3,[2,3],[1,2],]

 

use DFS (backtracking)

time = O(k * C(n,k)),space = O( C(n,k) )

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐