当需要对某一序列进行枚举取数时,可以使用二进制对是否取数进行标记。
以leetcode 491. 递增子序列为例
给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。
示例:
输入: [4, 6, 7, 7]
输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
说明:
给定数组的长度不会超过15。
数组中的整数范围是 [-100,100]。
给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。
使用二进制进行枚举,对所取序列用串哈希去重,代码:
class Solution {
List<Integer> temp = new ArrayList<Integer>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
Set<Integer> set = new HashSet<Integer>();
int n;
public List<List<Integer>> findSubsequences(int[] nums) {
n = nums.length;
for (int i = 0; i < (1 << n); ++i) {
findSubsequences(i, nums);
int hashValue = getHash(263, (int) 1E9 + 7);
if (check() && !set.contains(hashValue)) {
ans.add(new ArrayList<Integer>(temp));
set.add(hashValue);
}
}
return ans;
}
public void findSubsequences(int mask, int[] nums) {
temp.clear();
for (int i = 0; i < n; ++i) {
if ((mask & 1) != 0) {
temp.add(nums[i]);
}
mask >>= 1;
}
}
public int getHash(int base, int mod) {
int hashValue = 0;
for (int x : temp) {
hashValue = hashValue * base % mod + (x + 101);
hashValue %= mod;
}
return hashValue;
}
public boolean check() {
for (int i = 1; i < temp.size(); ++i) {
if (temp.get(i) < temp.get(i - 1)) {
return false;
}
}
return temp.size() >= 2;
}
}
也可以使用分支回溯进行解决,通过设置last上一次选取过的元素进行标记:
class Solution {
List<Integer> temp = new ArrayList<Integer>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
public List<List<Integer>> findSubsequences(int[] nums) {
dfs(0, Integer.MIN_VALUE, nums);
return ans;
}
public void dfs(int cur, int last, int[] nums) {
if (cur == nums.length) {
if (temp.size() >= 2) {
ans.add(new ArrayList<Integer>(temp));
}
return;
}
if (nums[cur] >= last) {
temp.add(nums[cur]);
dfs(cur + 1, nums[cur], nums);
temp.remove(temp.size() - 1);
}
if (nums[cur] != last) {
dfs(cur + 1, last, nums);
}
}
}
分支回溯另一应用:
leetcode 77. 组合
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
代码:
class Solution {
List<List<Integer>> ans=new LinkedList<List<Integer>>();
int N,K;
public List<List<Integer>> combine(int n, int k) {
List<Integer> L=new LinkedList<Integer>();
N=n;
K=k;
dfs(1,L);
return ans;
}
private void dfs(int cur,List<Integer> L){
if (L.size() + (N - cur + 1) < K) {
return;
}
if(L.size()==K){
ans.add(new LinkedList<Integer>(L));
return;
}
L.add(cur);
dfs(cur+1,L);
L.remove(L.size()-1);
dfs(cur+1,L);
}
}