zoukankan      html  css  js  c++  java
  • LeetCode

    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 };
  • 相关阅读:
    Cheatsheet: 2011 09.07 ~ 09.12
    Cheatsheet: 2011 10.01 ~ 10.10
    Cheatsheet: 2011 10.11 ~ 10.17
    Cheatsheet: 2011 09.01 ~ 09.06
    Cheatsheet: 2011 09.20 ~ 09.25
    Cheatsheet: 2011 08.17 ~ 08.22
    Cheatsheet: 2011 09.13 ~ 09.19
    Cheatsheet: 2011 08.08 ~ 08.16
    Cheatsheet: 2011 09.26 ~ 09.30
    Java05文件与流——课堂测试1
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3485751.html
Copyright © 2011-2022 走看看