设为首页 加入收藏

TOP

Leetcode dfs Combinations
2015-07-20 17:47:01 来源: 作者: 【 】 浏览:13
Tags:Leetcode dfs Combinations

Combinations

Total Accepted: 18327 Total Submissions: 60479My Submissions

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

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]



题意:给定两个数字 n 和 k,给出从1...n数字中取 k个的所有可能组合
思路:dfs
递归的深度为 k,第 i 层的第j个节点有 n - i - j 个选择分支
复杂度:时间 O(n^k),空间O(k)

vector
  
    > res;
int nn, kk;
void dfs(int cur, int start, vector
   
     &path){ if(cur == kk ){ res.push_back(path); } for(int i = start; i <= nn; i++){ path.push_back(i); dfs(cur + 1, i + 1, path); path.pop_back(); } } vector
    
      > combine(int n, int k){ nn = n, kk = k; vector
     
       path; dfs(0, 1, path); return res; }
     
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇UVA 11504 - Dominos(强连通分量) 下一篇Codeforces 104C Cthulhu dfs暴力..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·如何在 C 语言中管理 (2025-12-25 03:20:14)
·C语言和内存管理有什 (2025-12-25 03:20:11)
·为什么C语言从不被淘 (2025-12-25 03:20:08)
·常用meta整理 | 菜鸟 (2025-12-25 01:21:52)
·SQL HAVING 子句:深 (2025-12-25 01:21:47)