标签:
题目:
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], ]
代码:
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int> > ret; if ( n<k ) return ret; vector<int> tmp; Solution::dfs(ret, 1, k, n, 0,tmp); return ret; } static void dfs(vector<vector<int> >& ret, int index, int k, int n, int step, vector<int>& tmp) { if ( step==k ) { ret.push_back(tmp); return; } for ( size_t i = index; i <=n; ++i ) { tmp.push_back(i); Solution::dfs(ret, i+1, k, n, step+1, tmp); tmp.pop_back(); } } };
tips:
dfs解法。
几个参数的含义:
ret: 存储返回combination结果
index: 当前起始元素是多大
k,n:与题意所给相同
step:深入到第几层
思路:dfs的每层增加一个元素,直到深度等于k返回结果;如果从index开始的元素不足以打到深度k,则不会添加到ret中。
======================================
其实,可以不用传入6个参数,传入5个足以。代码如下:
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int> > ret; if ( n<k ) return ret; vector<int> tmp; Solution::dfs(ret, 1, k, n, tmp); return ret; } static void dfs(vector<vector<int> >& ret, int index, int k, int n, vector<int>& tmp) { if ( tmp.size()==k ) { ret.push_back(tmp); return; } for ( size_t i = index; i <=n; ++i ) { tmp.push_back(i); Solution::dfs(ret, i+1, k, n, tmp); tmp.pop_back(); } } };
用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
标签:
原文地址:http://www.cnblogs.com/xbf9xbf/p/4520749.html