首页 > 其他 > 详细

[LeetCode] Combinations

时间:2015-07-29 19:25:52      阅读:194      评论:0      收藏: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<vector<int>> combine(int n, int k) {
        vector<vector<int>> result;
        if(n < 0 || k < 0 || n < k){
            return result;
        }
        vector<int> item;
        combineHelper(n, k, item, result);
        
        return result;
    }
    
    void combineHelper(int n, int k, vector<int> item, vector<vector<int>>& 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

原文:http://blog.csdn.net/kangrydotnet/article/details/47130777

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!