combinations

所谓的组合就是从给定一组数据中选取若干个组合在一起,没有顺序的差别,所以很容易通过递归(dfs)来实现。

实例一(leetcode):

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],
]
#include <iostream>
#include <vector>
using std::vector;

class Solution{
public:
    vector<vector<int>> combinations(int n,int k)
    {
        vector<vector<int>> result;
        vector<int> path;
        dfs(n,k,1,0,path,result);
        return result;
    }
private:
    static void dfs(int n,int k,int start,int cur,
        vector<int> &path,vector<vector<int>> &result)
    {
        if(cur == k)
             return result.push_back(path);

        for(int i = start; i<=n; i++)
        {
            path.push_back(i);
            dfs(n,k,i+1,cur+1,path,result);
            path.pop_back();
        }
    }
};

int main()
{
    Solution s;
    vector<vector<int>> result;
    result = s.combinations(4, 2);
    return 0;
}

实例二:

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
using std::cout;

class Solution {
public:
    const vector<string> keyboard { " ", "", "abc", "def", // '0','1','2',...
                                        "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

    vector<string> letterCombinations(const string &digits) {
        vector<string> result;
        dfs(digits,0,"",result);
        return result;
    }
    
private:
    void dfs(const string& digits,int curr,string path,vector<string> &result)
    {
        if(curr == digits.size())
        {
            result.push_back(path);
            return;
        }
        for(auto c : keyboard[digits[curr]-'0'])
        {
            dfs(digits,curr+1,path+c,result);
        }
    }
};

int main()
{
    string input = "23";
    vector<string> result;
    Solution s;
    result = s.letterCombinations(input);
    for(string str : result)
    {
        cout << str << "\t";
    }
}

 

posted @ 2015-10-16 10:15  wxquare  阅读(290)  评论(0编辑  收藏  举报