backtracking 1

In a loop: forward(make a move), backtracking_func(dfs), then undo(retreat that move).

记录走过的路径和待选选项,遍历所有的选项,选择,backtrack,撤销

Permutations

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList();
        List<Integer> tmp = new ArrayList();
        permute(nums, tmp, res);
        return res;
    }
    
    public void permute(int[] nums, List<Integer> tmp, List<List<Integer>> res) {
        if (nums.length == tmp.size()) {
            res.add(new ArrayList(tmp));
            return;
        }
        
        int n = nums.length;
        for (int i = 0; i < n; ++i) {
            if (tmp.contains(nums[i])) continue;
            tmp.add(nums[i]);
            permute(nums, tmp, res);
            tmp.remove(tmp.size() - 1);
        }
    }
}

visited: memo

class Solution {
public:
    vector<vector<int>> permute(vector<int>& num) {
        vector<vector<int>> res;
        vector<int> out, visited(num.size(), 0);
        permuteDFS(num, 0, visited, out, res);
        return res;
    }
    void permuteDFS(vector<int>& num, int level, vector<int>& visited, vector<int>& out, vector<vector<int>>& res) {
        if (level == num.size()) {res.push_back(out); return;}
        for (int i = 0; i < num.size(); ++i) {
            if (visited[i] == 1) continue;
            visited[i] = 1;
            out.push_back(num[i]);
            permuteDFS(num, level + 1, visited, out, res);
            out.pop_back();
            visited[i] = 0;
        }
    }
};

N-queens

class Solution {
public:
    vector<vector<string>> res;
    
    vector<vector<string>> solveNQueens(int n) {
        vector<string> board(n, string(n, '.'));
        backtrack(board, 0);
        return res;
    }
    
    void backtrack(vector<string>& board, int row) {
        if (row == board.size()) {
            res.push_back(board);
            return;
        }
        
        int n = board.size();
        for (int col = 0; col < n; ++col) {
            if (!isValid(board, row, col)) continue;
            board[row][col] = 'Q';
            backtrack(board, row + 1);
            board[row][col] = '.';
        }
    }
    
    bool isValid(vector<string>& board, int row, int col) {
        int n = board.size();
        for (int i = 0; i < n; ++i) {
            if (board[i][col] == 'Q') return false;
        }
        for (int i = row-1, j=col+1; i>=0 && j < n; --i, ++j) {
            if (board[i][j] == 'Q') return false;
        }
        for (int i = row-1, j=col-1; i>=0 && j>=0; --i, --j) {
            if (board[i][j] == 'Q') return false;
        }
        return true;
    }
};

Permutation的backtrack参数没有变化是因为前面add元素到tmp中:已经有状态的变化了;而N-queens中元素还是没变:只是'.'变成了'Q', 而backtrack往下的步骤是row+1, 所以需要+1

Exercise

  • 401
  • 1863

推荐阅读更多精彩内容