设为首页 加入收藏

TOP

Combinations
2015-07-20 18:01:50 来源: 作者: 【 】 浏览:2
Tags: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],]

解题思路:

这是一个数学组合问题,即从n个数中随机选出k个数。可以用递归回溯来实现。

1 递归一次,填入一个数字
2 填入的数字,不能是小于当前数字的值,防止重复
3 回溯:记得pop_back()最后加上的一个数字,回溯到上一层。
4 结束条件:填写够了k个数字的时候,当前填写完毕,回溯

class Solution {
public:
    vector
  
    > combine(int n, int k) {/*排列组合问题*/
        vector
   
    > result; vector
    
      tmp; if (k > n || k == 0) return result; _combine(result, tmp, n, k, 1); return result; } void _combine(vector
     
      > &result, vector
      
       tmp, int n, int len, int start) {/*递归回溯*/ if (tmp.size() == len) { result.push_back(tmp); return; } for (int i = start; i < n+1; i++) { tmp.push_back(i); _combine(result, tmp, n, len, i+1); tmp.pop_back(); } } };
      
     
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇uva 1485 - Permutation Counting.. 下一篇poj1860--Currency Exchange

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: