惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
IT之家
IT之家
博客园_首页
量子位
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
博客园 - 聂微东
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
Hugging Face - Blog
Hugging Face - Blog
V
V2EX
爱范儿
爱范儿
大猫的无限游戏
大猫的无限游戏
宝玉的分享
宝玉的分享
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
雷峰网
雷峰网
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Google DeepMind News
Google DeepMind News
Microsoft Azure Blog
Microsoft Azure Blog
有赞技术团队
有赞技术团队
S
SegmentFault 最新的问题
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

博客园 - 来自海边的一片云

Binary Tree Maximum Path Sum 解题注意 CodingTMD’s Reading List De Bruijn 序列生成 Word Ladder I ,II 解题思路 suduko及8皇后问题及相关问题的解题思路 leetcode Word Break II 解题思路 Search for a string in an infinite stream of input string. 内存管理 Permutations leetcode Clone Graph leetcode 开弓没有回头箭 combination sum leetcode word break leetcode LRU cache Leetcode 重新试着写blog SQL injection Fuzz testing XML库的解析效率 Init()
Combinations leetcode 组合问题
来自海边的一片云 · 2014-02-08 · via 博客园 - 来自海边的一片云

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],
]

这类组合问题的思路常见的一个办法就是递归。
如果show(在结果里面show)那么该怎么处理,
如果not show (不出现在结果里面)该怎么处理。
void C(vector<int> array, int start, int k, vector<int> result, int index, vector<vector<int>>* finalvec)
{
    if (index == k) //found one
    {
        finalvec->push_back(result);
        return;
    }
    if (start<array.size())
    {
        //show
        result[index] = array[start];
        C(array, start + 1, k, result, index + 1, finalvec);

        C(array, start + 1, k, result, index, finalvec);
    }

}


vector<vector<int> > combine(int n, int k) {
    vector<int> array(n);
    vector<vector<int>> finalresult;
    for (int i = 1; i <= n; i++)
    {
        array[i - 1] = i;
    }
    vector<int> result(k);

    int start = 0;
    int index = 0;

    C(array, start, k, result, index, &finalresult);

    return finalresult;

}
类似的另外一个题目是 skip digits encoding, 比如说某个国家的人不喜欢4, 那么在所有的number里都不能出现4, 现在给定一个数 1876, 应该对应于real life的哪个数。

思路:
100~999中有多个数不包含digits 4, 因为是三位数,每个位置上出现的数字都是独立的,因为不能是4, 那每一位上不出现的可能性是C(9,1)
那么正好在 100~999中 C(9,1)* C(9,1)*C(9,1)
同样道理 10~99 中C(9,1)*c(9,1)
0~9 C(9,1)

int convert(int magic, int hatedigit)
{
    int outnumber = 0;
    int basep = 9;
    int p = 1;

    while (magic>0)
    {
        int digits = magic % 10;
        if (digits> hatedigit) outnumber += (digits - 1)* p;
        else outnumber += digits*p;
        p *= 9;
        magic = magic / 10;
    }
    return  outnumber;
}