[Leetcode] Combinations
来源:互联网 发布:网站阿里云备案要多久 编辑:程序博客网 时间:2024/06/06 01:40
题目链接在此
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],]
列出一个集合的所有组合情况。
如果k是固定的,那么k层for循环也能暴力地弄出来。
但是这里k是不固定的,那么要想办法模拟k层for循环。
嗯。回溯+递归。
class Solution {public:vector<vector<int> > combine(int n, int k) {vector<vector<int> > v;if (k < 1 || n < k)return v;vector<int> comb;backTrack(v, comb, n, k, 1);/*for (int i = 0; i < v.size(); i++) {for (int j = 0; j < v[i].size(); j++) {cout << v[i][j] << ' ';}cout << '\n';}*/return v;}private:void backTrack(vector<vector<int> > &v, vector<int> &comb, int n, int k, int start) {if (k == 0) {v.push_back(comb);return;}for (int i = start; i <= n; i++) {comb.push_back(i); // 如果集合S中的元素不是有序的1~n,把i改成S[i]即可backTrack(v, comb, n, k - 1, i + 1);comb.pop_back();}}};
0 0
- LeetCode: Combinations
- LeetCode: Combinations
- LeetCode Combinations
- [Leetcode] Combinations
- [LeetCode] Combinations
- Leetcode: Combinations
- LeetCode Combinations
- [Leetcode] Combinations
- [Leetcode] Combinations
- [leetcode] Combinations
- [LeetCode]Combinations
- [leetcode]Combinations
- LeetCode-Combinations
- [leetcode] Combinations
- LeetCode - Combinations
- 【Leetcode】Combinations
- Leetcode: Combinations
- 【leetcode】Combinations
- 【Android】仿微信的图片选择app ( 图片异步加载,缩放等)
- CSS中让字体变透明
- 面向对象思想
- Mysql逻辑或逻辑与混合使用
- mysql 2
- [Leetcode] Combinations
- Nginx配置----安全篇
- win7手动添加开机启动项
- LDA
- jasper报表添加显示字段
- js面向对象编程-高级内容
- Nginx配置---性能篇
- openwrt启动过程中
- Android基础之在程序代码中引用资源(color&mipmap&string)