# backtracking 1

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

## 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()) {
return;
}

int n = nums.length;
for (int i = 0; i < n; ++i) {
if (tmp.contains(nums[i])) continue;
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

• 401
• 1863