码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Combinations

时间:2015-04-15 11:25:44      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:leetcode   回溯   

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

这道题感觉跟Subsets II有一点相似,都是通过回溯来按位生成题解。
本来想用一个visit数组记录每一个数字出现的情况,但因为这一题1~n是严格递增的,所以并没有必要。

class Solution {
public:
    //int visited[10000] = {0};
    void f(int step,int n,int k,vector<int> &res,vector<vector<int>> &ans){
        if(res.size() == k){
            ans.push_back(res);
            return ;
        } 
        for(int i = step;i <= n;i++){
            res.push_back(i);
            f(i+1,n,k,res,ans);
            res.pop_back();
        }
    }
    vector<vector<int> > combine(int n, int k) {
        vector<vector<int>> ans;
        vector<int> res;
        f(1,n,k,res,ans);
        return ans;
    }
};

[leetcode]Combinations

标签:leetcode   回溯   

原文地址:http://blog.csdn.net/iboxty/article/details/45055389

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!