leetcode——backtracking and array 递归类问题

来源:互联网 发布:倪妮和angelababy 知乎 编辑:程序博客网 时间:2024/05/16 12:07

        Combination Sum:

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

subsets:

Given a set of distinct integers, nums, return all possible subsets.


word search:

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

        这三类都是给定了一个数组,然后找出满足相应条件的特定集合,属于数组中的递归类问题,大致思想就是,将问题分为一模一样的子问题利用相同的函数进行处理。这三个问题都新建了一个函数dfs,用来递归调用。分析递归类问题,最重要的一点就是要有块的思想,分析第一个数时,就把后面的一堆看成另一块另一个数,要有整体思想,只需要分析第一个数怎么处理,其他都是一样的。

       递归问题需要想清楚两个问题:1.怎么调用自己;2.什么时候结束。


    一维数组:

     void dfs(vector<int>& subset,vector<vector<int>>& result,int index,vector<int>& nums){
        result.push_back(subset);   \\最后返回的结果,所有答案的集合
        for(int i=index;i<nums.size();i++){     \\index一般从0开始,循环选择数组中的每一个数,当循环到数组结束时就结束
            subset.push_back(nums[i]);         \\将当前的数放进本次循环的答案中
            dfs(subset,result,i+1,nums);     \\后面的i+1个数调用自己
            subset.pop_back();          \\不选自己
        }

   二维数组:

bool search(vector<vector<char>>& board, string str, int i, int j, vector<vector<bool>>& visit){
if (str.empty()) return true;          \\当循环到目标字符串结束时结束
vector<int> vec{ -1, 0, 0, 1 };      \\搜索上下左右几个数时,可以利用状态机来简化代码
vector<int> hor{ 0, -1, 1, 0 };
visit[i][j] = true;
for (int k = 0; k<4; k++){
if ((i + vec[k]) >= 0&&(i + vec[k] )< board.size() && (j + hor[k]) >= 0 && (j + hor[k]) < board[0].size()){
if (board[i + vec[k]][j + hor[k]] == str[0] && visit[i + vec[k]][j + hor[k]] == false){
visit[i + vec[k]][j + hor[k]] = true;
if (str.length() == 1 || search(board, str.substr(1, str.length() - 1), (i + vec[k]), (j + hor[k]), visit)) return true;
visit[i + vec[k]][j + hor[k]] = false;
}
}
}
visit[i][j] = false;
return false;
}

0 0
原创粉丝点击