分类
组合问题:N个数里面按一定规则找出k个数的集合
切割问题:一个字符串按一定规则有几种切割方式
子集问题:一个N个数的集合里有多少符合条件的子集
排列问题:N个数按一定规则全排列,有几种排列方式
棋盘问题:N皇后,解数独等等
例题1 组合总和 III
https://leetcode.cn/problems/combination-sum-iii/description/
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
nums=list(range(1,10))
ans=[]
tmp=[]
def backtrace(nums,index):
if len(tmp)==k and sum(tmp)==n:
ans.append(tmp[:])
return
for i in range(index,9):
if len(tmp)==k-1 and n-sum(tmp)>9:
break
else:
tmp.append(nums[i])
backtrace(nums,i+1)
tmp.pop()
backtrace(nums,0)
return ans
class Solution {
private int k;
private int n;
private int total=0;
private final List<Integer> path= new ArrayList<>();
private final List<List<Integer>> ans= new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
this.k=k;
this.n=n;
backtrace(1);
return ans;
}
public void backtrace(int index ){
if (path.size()==k && total==n){
ans.add(new ArrayList<>(path));
}
for(int i=index;i<=9;i++){
if (path.size()==k-1 && n-total>9)break;
path.add(i);
total+=i;
backtrace(i+1);
total-=i;
path.remove(path.size()-1);
}
}
}
例题2 分割回文串
https://leetcode.cn/problems/palindrome-partitioning/description/
class Solution:
def partition(self, s: str) -> List[List[str]]:
n=len(s)
ans=[]
tmp=[]
def ifduichen(s):
if len(s)==0:return False
n=len(s)
left=0
right=n-1
while left<right:
if s[left]!= s[right]:
return False
left+=1
right-=1
return True
def backtrace(s,index):
if index>n-1:
ans.append(tmp[:])
for i in range(index+1,n+1):
if ifduichen(s[index:i]):
tmp.append(s[index:i])
backtrace(s,i)
tmp.pop()
else:
continue
backtrace(s,0)
return ans
class Solution {
private List<List<String>> ans = new ArrayList<>();
private List<String> path = new ArrayList<>();
private int n;
public List<List<String>> partition(String s) {
this.n=s.length();
backtrace(s,0);
return ans;
}
public boolean ifsymmetry(String s){
int left=0,right=s.length()-1;
char[] sarr=s.toCharArray();
while (left<right){
if(sarr[left]!=sarr[right])return false;
left+=1;
right-=1;
}
return true;
}
public void backtrace(String s,int index){
if(index>=n){
ans.add(new ArrayList<>(path));
}
for(int i=index+1;i<=n;i++){
if(ifsymmetry(s.substring(index,i))){
path.add(s.substring(index,i));
backtrace(s,i);
path.remove(path.size()-1);
}
}
}
}
例题3 复原 IP 地址
https://leetcode.cn/problems/restore-ip-addresses/description/
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
path=[]
ans=[]
def backtrace(s,index):
if len(path)==4:
if index>=len(s):
ans.append('.'.join(path[:]))
return
for i in range(index+1,len(s)+1):
if self.ifvalid(s[index:i]):
# print(s[index:i])
path.append(s[index:i])
backtrace(s,i)
path.pop()
backtrace(s,0)
return ans
def ifvalid(self,s):
if len(s)>1 and s[0]!='0' and eval(s)>0 and eval(s)<=255:
return True
elif len(s)==1 and eval(s)>=0 and eval(s)<=255:
return True
else:
return False