一、力扣
1、在排序数组中查找元素的第一个和最后一个位置
34. 在排序数组中查找元素的第一个和最后一个位置

class Solution {
public int[] searchRange(int[] nums, int target) {
int start = lowerBound(nums, target);
if (start == nums.length || nums[start] != target) {
return new int[]{-1, -1};
}
int end = lowerBound(nums, target + 1) - 1;
return new int[]{start, end};
}
private int lowerBound(int[] nums, int target) {
int left = 0;
int right = nums.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
2、字符串解码
394. 字符串解码

class Solution {
public String decodeString(String s) {
ArrayDeque<Integer> stnum = new ArrayDeque<>();
ArrayDeque<StringBuilder> stsb = new ArrayDeque<>();
StringBuilder ans = new StringBuilder();
int k = 0;
for (int i = 0; i < s.length(); i++) {
char temp = s.charAt(i);
if (Character.isDigit(temp)) {
k = k * 10 + (temp - '0');
} else if (temp == '[') {
stnum.push(k);
stsb.push(ans);
k = 0;
ans = new StringBuilder();
} else if (temp == ']') {
int count = stnum.pop();
StringBuilder col = stsb.pop();
while (count > 0) {
col.append(ans);
count--;
}
ans = col;
} else {
ans.append(temp);
}
}
return ans.toString();
}
}
3、子集
78. 子集

class Solution {
List<List<Integer>> res;
List<Integer> path;
int[] nums;
public List<List<Integer>> subsets(int[] nums) {
res=new ArrayList<>();
path=new ArrayList<>();
this.nums=nums;
dfs(0);
return res;
}
public void dfs(int start){
res.add(new ArrayList<>(path));
for(int i=start;i<nums.length;i++){
path.add(nums[i]);
dfs(i+1);
path.removeLast();
}
}
}
4、子集 II
90. 子集 II

class Solution {
List<List<Integer>> res;
List<Integer> path;
int[] nums;
public List<List<Integer>> subsetsWithDup(int[] nums) {
res=new ArrayList<>();
path=new ArrayList<>();
Arrays.sort(nums);
this.nums=nums;
int[] vis=new int[nums.length];
dfs(0,vis);
return res;
}
public void dfs(int start,int[] vis){
res.add(new ArrayList<>(path));
for(int i=start;i<nums.length;i++){
if(i>0&&nums[i]==nums[i-1]&&vis[i-1]==0) continue;
path.add(nums[i]);
vis[i]=1;
dfs(i+1,vis);
path.removeLast();
vis[i]=0;
}
}
}
5、非递减子序列
491. 非递减子序列

class Solution {
List<List<Integer>> res;
List<Integer> path;
int[] nums;
int n;
public List<List<Integer>> findSubsequences(int[] nums) {
n=nums.length;
res=new ArrayList<>();
path=new ArrayList<>();
this.nums=nums;
backtracking(0);
return res;
}
public void backtracking(int start){
if(path.size()>=2){
res.add(new ArrayList<>(path));
}
Set<Integer> set=new HashSet<>();
for(int i=start;i<n;i++){
if(path.size()>0&&nums[i]<path.get(path.size()-1)) continue;
if(set.contains(nums[i])) continue;
set.add(nums[i]);
path.add(nums[i]);
backtracking(i+1);
path.removeLast();
}
}
}