Leetcode Combinations
生活随笔
收集整理的這篇文章主要介紹了
Leetcode Combinations
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
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:
典型暴力搜索題,一共有n種可能,對于每個元素i,即可以放入結(jié)果中,又可以不放入結(jié)果中,
注意搜索時剪枝,即每種結(jié)果有k個值,大于k個的剪掉即可 class Solution { public:typedef vector<vector<int> > VectorArray;int m_n,m_k;VectorArray result;vector<int> solution;void dfs(int level){if( solution.size() == m_k){result.push_back(solution);return;}for(int i = level; i <= m_n; ++ i){solution.push_back(i);dfs(i+1);solution.pop_back();}}VectorArray combine(int n, int k){m_n = n, m_k = k;dfs(1);return result;} };
?
轉(zhuǎn)載于:https://www.cnblogs.com/xiongqiangcs/p/3801270.html
總結(jié)
以上是生活随笔為你收集整理的Leetcode Combinations的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 锦瑟
- 下一篇: zoj 3791 An Easy Gam