Thursday, June 27, 2013

combinations@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
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],
]
» Solve this problem

这些题都和permutations一个思路,把permutations给弄明白了,这些枚举的方法就搞定了,其实这些题的本质就是搜索,或者search,又或者是pointers题,就是用一种正确而且全面的方式去搜索这个数据结构。很多算法的本质也是做同一件事情,比如树的遍历,比如图的bfs, dfs, 全都是一种如何去遍历or iterate through一个数据结构的方法。

写熟一点儿,发现pattern。

1 comment:

  1. 不用visited了:

    void combination(int n, int k, int offset, vector>& result, vector& solution)
    {
    if (solution.size() == k)
    {
    result.push_back(solution);
    }else
    {
    for (int i = offset; i <= n; i++)
    {
    solution.push_back(i);
    combination(n, k, i+1, result, solution);
    solution.pop_back();
    }
    }
    }

    vector > combine(int n, int k)
    {
    vector> result;
    vector solution = vector(0);

    combination(n, k, 1, result, solution);

    return result;
    }

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...