Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
class Solution {
public:
void nextPermutation(vector<int> &num) {
next_permutation(num.begin(), num.end());
}
};
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
class Solution {
vector<bool> row, left, right;
void fill(const int col, const int n, vector<string> &board, vector<vector<string> > &ans) {
if (col == n) {
ans.push_back(board);
return;
}
for (int i = 0; i < n; ++i) {
if (row[i] || left[i - col + n] || right[i + col])
continue;
row[i] = left[i - col + n] = right[i + col] = true;
board[i][col] = 'Q';
fill(col + 1, n, board, ans);
row[i] = left[i - col + n] = right[i + col] = false;
board[i][col] = '.';
}
}
public:
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > ans;
string raw(n, '.');
vector<string> board(n, raw);
row.resize(n, false);
left.resize(2 * n, false);
right.resize(2 * n, false);
fill(0, n, board, ans);
return ans;
}
};
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution {
vector<bool> row, left, right;
void fill(const int col, const int n, int &ans) {
if (col == n) {
++ans;
return;
}
for (int i = 0; i < n; ++i) {
if (row[i] || left[i - col + n] || right[i + col])
continue;
row[i] = left[i - col + n] = right[i + col] = true;
fill(col + 1, n, ans);
row[i] = left[i - col + n] = right[i + col] = false;
}
}
public:
int totalNQueens(int n) {
row.resize(n, false);
left.resize(2 * n, false);
right.resize(2 * n, false);
int ans = 0;
fill(0, n, ans);
return ans;
}
};
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
class Solution {
public:
int hammingWeight(uint32_t n) {
int c = 0;
for (; n; ++c)
n &= (n - 1);
return c;
}
};