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

<LeetCode OJ> 77. Combinations

时间:2016-03-09 16:10:11      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

Total Accepted: 69360 Total Submissions: 206274 Difficulty: Medium

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

Subscribe to see which companies asked this question

Hide Tags
 Backtracking
Hide Similar Problems
 (M) Combination Sum (M) Permutations

分析:

回溯法的典型

class Solution {
public:
    void dfs(vector<vector<int > > &ans, vector<int> &subans, int start, int n, int k)
    {
        if (subans.size() == k)//已经获得答案,并且回溯
        {
            ans.push_back(subans); 
            return ;//回溯
        }
        for (int i = start; i <= n; i++)
        {
            subans.push_back(i);
            dfs(ans, subans, i + 1, n, k);
            subans.pop_back(); // 回溯去掉末尾元素
        }
    }
    vector<vector<int> > combine(int n, int k) {
        vector<vector<int > > result;
        if (n < k || k == 0) 
            return result;
        vector<int> subres;
        dfs(result, subres, 1, n, k);
        return result;
    }
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50835803

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

<LeetCode OJ> 77. Combinations

标签:

原文地址:http://blog.csdn.net/ebowtang/article/details/50835803

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