题目:

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:

  1. [
  2. [2,4],
  3. [3,4],
  4. [2,3],
  5. [1,2],
  6. [1,3],
  7. [1,4],
  8. ]

代码:

  1. class Solution {
  2. public:
  3. vector<vector<int>> combine(int n, int k) {
  4. vector<vector<int> > ret;
  5. if ( n<k ) return ret;
  6. vector<int> tmp;
  7. Solution::dfs(ret, , k, n, ,tmp);
  8. return ret;
  9. }
  10. static void dfs(vector<vector<int> >& ret, int index, int k, int n, int step, vector<int>& tmp)
  11. {
  12. if ( step==k )
  13. {
  14. ret.push_back(tmp);
  15. return;
  16. }
  17. for ( size_t i = index; i <=n; ++i )
  18. {
  19. tmp.push_back(i);
  20. Solution::dfs(ret, i+, k, n, step+, tmp);
  21. tmp.pop_back();
  22. }
  23. }
  24. };

tips:

dfs解法。

几个参数的含义:

ret: 存储返回combination结果

index: 当前起始元素是多大

k,n:与题意所给相同

step:深入到第几层

思路:dfs的每层增加一个元素,直到深度等于k返回结果;如果从index开始的元素不足以打到深度k,则不会添加到ret中。

======================================

其实,可以不用传入6个参数,传入5个足以。代码如下:

  1. class Solution {
  2. public:
  3. vector<vector<int>> combine(int n, int k) {
  4. vector<vector<int> > ret;
  5. if ( n<k ) return ret;
  6. vector<int> tmp;
  7. Solution::dfs(ret, , k, n, tmp);
  8. return ret;
  9. }
  10. static void dfs(vector<vector<int> >& ret, int index, int k, int n, vector<int>& tmp)
  11. {
  12. if ( tmp.size()==k )
  13. {
  14. ret.push_back(tmp);
  15. return;
  16. }
  17. for ( size_t i = index; i <=n; ++i )
  18. {
  19. tmp.push_back(i);
  20. Solution::dfs(ret, i+, k, n, tmp);
  21. tmp.pop_back();
  22. }
  23. }
  24. };

用tmp.size()代替step,代码跟简洁一些,因此更推崇后一种方法。

=======================================

leetcode写到这里有些感觉了,搜了一下dfs bfs的模板相关的内容,基本跟实战中的经验差不多:

http://blog.csdn.net/fightforyourdream/article/details/12866861

http://www.cnblogs.com/HectorInsanE/archive/2010/11/09/1872656.html

=======================================

再补上一种迭代的解法,如下:

  1. class Solution {
  2. public:
  3. vector<vector<int>> combine(int n, int k) {
  4. vector<vector<int> > ret;
  5. // corner cases
  6. if ( n<k || k== ) return ret;
  7. // initialization
  8. for ( int i = ; i < n-k+; ++i )
  9. {
  10. vector<int> tmp;
  11. tmp.push_back(i+);
  12. ret.push_back(tmp);
  13. }
  14. // combines
  15. for ( int i = ; i < k-; ++i )
  16. {
  17. vector<vector<int> > tmp = ret;
  18. ret.clear();
  19. for ( int j = ; j < tmp.size(); ++j )
  20. {
  21. int curr = tmp[j].back();
  22. for ( int v = curr+; v <= n; ++v )
  23. {
  24. vector<int> ori = tmp[j];
  25. ori.push_back(v);
  26. ret.push_back(ori);
  27. }
  28. }
  29. }
  30. return ret;
  31. }
  32. };

tips:

1. 这种迭代方式返回的组合内部都是由小到大排序的。

2. intialization的含义是”组合首个元素最小到最大“(比如n=4,k=2 按照原则1,则首个元素最大取到3,因为比4小的元素没有了不足以满足k=2的条件)

3. 每轮迭代,先取出来当前组合最后一个元素(最大的)curr;再从curr+1到n挨个取值,补到tmp[j]的后面,构成新的组合。

4. 控制迭代的次数是k-1次(因为initialization已经算了一次)

===============================================

第二次过这道题,用dfs过的,传入参数比第一次过更简洁一些。

  1. class Solution {
  2. public:
  3. vector<vector<int> > combine(int n, int k)
  4. {
  5. vector<vector<int> > ret;
  6. vector<int> tmp;
  7. Solution::dfs(ret, tmp, n, k);
  8. return ret;
  9. }
  10. static void dfs(
  11. vector<vector<int> >& ret,
  12. vector<int>& tmp,
  13. int n, int k)
  14. {
  15. if ( tmp.size()==k )
  16. {
  17. ret.push_back(tmp);
  18. return;
  19. }
  20. int index = tmp.empty() ? : tmp.back();
  21. for ( int i=index+; i<=n; ++i )
  22. {
  23. tmp.push_back(i);
  24. Solution::dfs(ret, tmp, n, k);
  25. tmp.pop_back();
  26. }
  27. }
  28. };

【Combinations】cpp的更多相关文章

  1. 【Permutations】cpp

    题目: Given a collection of numbers, return all possible permutations. For example,[1,2,3] have the fo ...

  2. 【Subsets】cpp

    题目: Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset ...

  3. 【Anagrams】 cpp

    题目: Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will ...

  4. 蓝桥杯 【dp?】.cpp

    题意: 给出一个2*n的方格,当刷完某一个方格的漆后可以且只可以走到相邻的任何一格,即上 下 左 右 左上 左下 右上 右下.可以从任意一个格子开始刷墙,问有多少种刷法,因为随着n的增大方案数会变多, ...

  5. 【Triangle 】cpp

    题目: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjace ...

  6. 【N-Queens】cpp

    题目: The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two que ...

  7. 【Candy】cpp

    题目: There are N children standing in a line. Each child is assigned a rating value. You are giving c ...

  8. 【4Sum】cpp

    题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = ...

  9. 【3Sum】cpp

    题目: Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find al ...

随机推荐

  1. Hibernate笔记2

    一.持久化类 1.持久化标识OID     数据库中叫做主键,对应实体的ID属性即为OID;Hibernate通过OID区分两个对象是否为同一对象;OID的生成一般交由程序自动处理; 2.持久化类   ...

  2. TX Text Control X10独家揭秘之使用对象作为数据源

    文档处理控件TX Text Control即将发布的X10版本,将升级重点还是放到了其比较优势的流式布局报表设计和生成上.慧都获得了来自其开发商Text Control GmbH公司的一手资料,迫不及 ...

  3. sublimetext3安装配置

    官网:http://www.sublimetext.com/ 中文官网:http://www.sublimetextcn.com/ 包管理器:https://packagecontrol.io/ins ...

  4. jQuery-动画animate() 方法操作 CSS 属性

    语法: $(selector).animate({params},speed,callback); 多个params 之间用逗号(,)隔开. 必须使用 Camel 标记法书写所有的属性名,比如,必须使 ...

  5. LeetCode Remove Duplicates from Sorted Array II 删除整型数组中的重复元素并返回剩下元素个数2

    class Solution { public: int removeDuplicates(int A[], int n) { ],*e=&A[]; //s指向“连续数字”的第一个,e往后遍历 ...

  6. Head First HTML与CSS阅读笔记(二)

    上一篇Head First HTML与CSS阅读笔记(一)中总结了<Head First HTML与CSS>前9章的知识点,本篇则会将剩下的10~15章内容进行总结,具体如下所示. div ...

  7. 简析平衡树(一)——替罪羊树 Scapegoat Tree

    前言 平衡树在我的心目中,一直都是一个很高深莫测的数据结构.不过,由于最近做的题目的题解中经常出现"平衡树"这三个字,我决定从最简单的替罪羊树开始,好好学习平衡树. 简介 替罪羊树 ...

  8. pip 安装出现异常

    MacBookPro:~ mac$ pip install numpy Collecting numpy Downloading numpy-1.13.1-cp35-cp35m-macosx_10_6 ...

  9. 三种序列化方式存取redis的方法

    常见的的序列化反序列方式的效率: protoBuf(PB) > fastjson > jackson > hessian > xstream > java 数据来自于:h ...

  10. ubuntu install oracle jdk

    .Download the required tarball from here .unzip this tarball using "tar -zxvf tarball_name .cre ...