【Leetcode】【Medium】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],
]

解题思路:

实现"combination组合"(类比"permutation排列",见Leetcode:Permutation

还是回溯穷举的思想,模拟组合的过程,即从n个数中选k个;则在剩余数够k个前提下,每个数都可以选或者不选;

注意递归时要保证剩余可选的数字个数,能满足要求,不然浪费函数栈的资源;

 

解题步骤:

1、建立一个数组ans,建立一个二维数组lst,用于保存所有满足条件的ans;

2、调用递归子函数,输入为lst(引用可变),ans(值传递不变),总字母数n,还需要挑选的字母数k,当前遍历的起始下标idx:

  (1)如果当前ans长度=k,表明挑选结束,将ans放入lst中,并返回;

  (2)从i = idx开始遍历,到i = n-k+1(满足剩余数够挑选):

    a. 将当前i插入ans中,继续下一层递归;

    b. 将刚才放入ans中的i pop出,继续循环;

 

代码:

 1 class Solution {
 2 public:
 3     vector<vector<int>> combine(int n, int k) {
 4         vector<vector<int>> lst;
 5         vector<int> ans;
 6         Backtracking(lst, ans, n, k, 1);
 7         return lst;
 8     }
 9     
10     void Backtracking(vector<vector<int>> &lst, vector<int> ans, int n, int k, int idx) {
11         if (k == 0) {
12             lst.push_back(ans);
13             return;
14         }
15         
16         for (int i = idx; i <= n - k + 1; ++i) {
17             ans.push_back(i);
18             Backtracking(lst, ans, n, k - 1, i + 1);
19             ans.pop_back();
20         }
21     }
22 };

 

 


posted @ 2015-04-21 23:03  胡潇  阅读(173)  评论(0编辑  收藏  举报