随笔- 509  文章- 0  评论- 151  阅读- 22万 

Combinations

2013.12.22 05:17

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],
]

Solution:

  Combination and permutation problems are usually solved with DFS recursion.

  When solving C(n, k), we pick one element from the candidate set, and solve C(n - 1, k - 1) with the remaining set.

  Time complexity is, eh ...O(C(n, 0) + C(n, 1) + ... + C(n, k)), because the subset (1, 3, 4) comes only after you've searched (1) and (1, 3). ALL smaller subsets must be traversed to get the desired subsets of size k. Space complexity is O(n).

Accepted code:

复制代码
 1 // 1AC, very well
 2 class Solution {
 3 public:
 4     vector<vector<int> > combine(int n, int k) {
 5         // IMPORTANT: Please reset any member data you declared, as
 6         // the same Solution instance will be reused for each test case.
 7         int i;
 8         for(i = 0; i < result.size(); ++i){
 9             result[i].clear();
10         }
11         result.clear();
12         
13         if(n <= 0 || k <= 0){
14             return result;
15         }
16         
17         arr = new int[n];
18         dfs(0, 0, n, k);
19         delete[] arr;
20         
21         return result;
22     }
23 private:
24     vector<vector<int>> result;
25     int *arr;
26     
27     void dfs(int idx, int cnt, int n, int k) {
28         int i;
29         
30         if(cnt == k){
31             result.push_back(vector<int>());
32             for(i = 0; i < k; ++i){
33                 result[result.size() - 1].push_back(arr[i]);
34             }
35             return;
36         }
37         
38         // trim redundant path to save some time
39         if(idx + (k - cnt) > n){
40             return;
41         }
42         
43         for(i = idx; i < n; ++i){
44             arr[cnt] = i + 1;
45             dfs(i + 1, cnt + 1, n, k);
46         }
47     }
48 };
复制代码

 

 posted on   zhuli19901106  阅读(250)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示