递归和回溯法

17. Letter Combinations of a Phone Number

vector<string> letterCombinations(string digits) {
    vector<string> result;
    if(digits.empty()) return vector<string>();
    static const vector<string> v = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    result.push_back("");   // add a seed for the initial case
    for(int i = 0 ; i < digits.size(); ++i) {
        int num = digits[i]-'0';
        if(num < 0 || num > 9) break;
        const string& candidate = v[num];
        if(candidate.empty()) continue;
        vector<string> tmp;
        for(int j = 0 ; j < candidate.size() ; ++j) {
            for(int k = 0 ; k < result.size() ; ++k) {
                tmp.push_back(result[k] + candidate[j]);
            }
        }
        result.swap(tmp);
    }
    return result;
}

93. Restore IP Addresses


131. Palindrome Partitioning


排列组合

46. Permutations

class Solution {
public:
    vector<vector<int> > permute(vector<int> &num) {
        vector<vector<int> > result;

        permuteRecursive(num, 0, result);
        return result;
    }

    // permute num[begin..end]
    // invariant: num[0..begin-1] have been fixed/permuted
    void permuteRecursive(vector<int> &num, int begin, vector<vector<int> > &result)    {
        if (begin >= num.size()) {
            // one permutation instance
            result.push_back(num);
            return;
        }

        for (int i = begin; i < num.size(); i++) {
            swap(num[begin], num[i]);
            permuteRecursive(num, begin + 1, result);
            // reset
            swap(num[begin], num[i]);
        }
    }
};

47. Permutations II


组合问题

77. Combinations

剪枝思想

39. Combination Sum


40. Combination Sum II


216. Combination Sum III


78. Subsets


90. Subsets II


401. Binary Watch


二维平面上使用回溯法


79. Word Search

floodfill算法,深度优先遍历

200. Number of Islands


130. Surrounded Regions


417. Pacific Atlantic Water Flow


N皇后问题

51. N-Queens


52. N-Queens II


37. Sudoku Solver

你可能感兴趣的:(OJ分门别类笔记汇总)