ITPub博客

首页 > > > [LeetCode] Combinations

[LeetCode] Combinations

作者:Ruiyuan Li 时间:2015-07-29 00:00:00 0 删除 编辑

Combinations

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

解题思路:

这道题的题意是找到1-n的数字中找出k个数的所有组合。可以采用递归回溯法。比较简单。

class Solution {
public:
    vector> combine(int n, int k) {
        vector> result;
        if(n < 0 || k < 0 || n < k){
            return result;
        }
        vector item;
        combineHelper(n, k, item, result);
        
        return result;
    }
    
    void combineHelper(int n, int k, vector item, vector>& result){
        int size = item.size();
        if(size>=k){
            result.push_back(item);
            return;
        }
        int last = size==0 ? 0 : item[size - 1];
        if(n - last + size < k){    //无法达到k的大小了
            return;
        }
        for(int i = last + 1; i <= n; i++){
            item.push_back(i);
            combineHelper(n, k, item, result);
            item.pop_back();
        }
    }
};


转载请注明: » [LeetCode] Combinations
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4825