LeetCode: Combinations 递归回溯 2种实现方法
来源:互联网 发布:网络电视wifi连接不了 编辑:程序博客网 时间:2024/04/29 17:09
题目:
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> > sumv; if(k < 1 || k > n) return sumv; vector<int> tempv; //comb1(sumv,tempv,n,k,1); comb2(sumv,tempv,n,k,1); return sumv; } /* void comb1(vector<vector<int> >&sumv, vector<int>& tempv,int n,int k,int start) { for(int i= start; i <= n;i++) { tempv.push_back(i); if(tempv.size() == k) { sumv.push_back(tempv); tempv.pop_back(); continue; } if(i < n) comb(sumv,tempv,n,k,i+1); tempv.pop_back(); } } */ void comb2(vector<vector<int> >&sumv, vector<int>& tempv,int n,int k, int start) { if(k==0) { sumv.push_back(tempv); return ; } for(int i = start; i <= n; i++) { tempv.push_back(i); comb2(sumv, tempv,n,k-1,i+1); tempv.pop_back(); } }};
0 0
- LeetCode: Combinations 递归回溯 2种实现方法
- 77.leetcode Combinations(medium)[回溯递归]
- [leetcode][回溯] Combinations
- 17.leetcode Letter Combinations of a Phone Number(meidum)[递归回溯]
- LeetCode 17. Letter Combinations of a Phone Number 递归回溯法
- [C++]LeetCode: 83 Combinations (回溯法)
- LeetCode-77-Combinations(回溯法)-Medium
- (回溯法)LeetCode#77. Combinations
- 每日AC--leetCode--PalindromePartitioning--回溯法 递归实现
- leetcode--递归、回溯和分治
- LeetCode 22:Generate Parentheses的递归,回溯两种解法
- [leetcode][回溯] Letter Combinations of a Phone Number
- 八皇后 回溯递归实现
- leetcode 77. Combinations-排列|递归|非递归|Java|Python
- [LeetCode]Permutations(回溯&&DFS&&递归!!!!)
- [LeetCode]Permutations II(!!!!!DFS递归&&回溯)
- Leetcode|Combination Sum II[递归回溯]
- leetcode 22. Generate Parentheses-回溯|递归
- POJ Dropping tests
- java.lang.IllegalArgumentException: Can not set XXX to com.sun.proxy.$Proxy28
- MVP模式与MVC模式
- Boost.Interprocess使用手册翻译之一:介绍 (Introduction)
- IOS 开发缓存机制----内存缓存机制
- LeetCode: Combinations 递归回溯 2种实现方法
- 学习笔记:如何开个有效的站会
- 为什么微波炉加热某些食物会爆炸?
- Storm实战之概念简介
- Boost.Interprocess使用手册翻译之二:快速指南 (Quick Guide for the Impatient)
- swift 语言更新进度
- flex 上传整理
- 可靠指标与失效概率
- 一个阳历转农历的java程序