【Leetcode】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],
]
 1 class Solution {
 2 public:
 3     vector<vector<int> > combine(int n, int k) {
 4         vector<vector<int>> result;
 5         vector<bool> used(n + 1, false);
 6         vector<int> path;
 7         dfs(n, k, used, path, result);
 8         return result;
 9     }
10 private:
11     void dfs(int n, int k, vector<bool> & used, vector<int> &path, vector<vector<int>> &result) {
12         if (path.size() == k) {
13             result.push_back(path);
14             return;
15         }
16         for (int i = path.empty() ? 1 : path.back() + 1; i <= n - k + 1 + path.size(); ++i) {
17             if (!used[i]) {
18                 used[i] = true;
19                 path.push_back(i);
20                 dfs(n, k, used, path, result);
21                 path.pop_back();
22                 used[i] = false;
23             }
24         }
25     }
26 };
View Code

排列类似,只是dfs的时候的搜索的策略稍有不同。

posted @ 2014-03-19 13:23  小菜刷题史  阅读(238)  评论(0编辑  收藏  举报