分类
组合问题: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[:])returnfor i in range(index,9):if len(tmp)==k-1 and n-sum(tmp)>9:breakelse: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 Falsen=len(s)left=0right=n-1while left<right:if s[left]!= s[right]:return Falseleft+=1right-=1return Truedef 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:continuebacktrace(s,0)return ans