完全平方数
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, …)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
链接:https://leetcode-cn.com/problems/perfect-squares
public int NumSquares(int n) {
var dp=new int[n+1];
if(n<1) return 0;
dp[1]=1;
for(var i=2;i<=n;i++){
if(i*i<=n) dp[i*i]=1;
if(dp[i]==1) continue;
var min=int.MaxValue;
for(var j=1;j*j<i;j++){
min=Math.Min(min, 1+dp[i-j*j]);
}
dp[i] = min;
//Console.WriteLine(i+" "+dp[i]);
}
return dp[n];
}
public bool isSquar(int n){
var s=Math.Sqrt(n);
return s*s==n;
}
分割回文串 II
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回符合要求的最少分割次数。
示例:
输入: “aab”
输出: 1
解释: 进行一次分割就可将 s 分割成 [“aa”,“b”] 这样两个回文子串。
链接:https://leetcode-cn.com/problems/palindrome-partitioning-ii
public class Solution {
public int MinCut(string s) {
if(string.IsNullOrEmpty(s)){
return 0;
}
int len = s.Length;
var dp = new bool[s.Length,s.Length];
int[] cut = new int[s.Length];
for(int i = 0; i < len; i++){
//最大划分就是i次
cut[i]= i;
for(int j = 0; j <= i; j++){
if(s[i] == s[j] &&(i-j <= 1 || dp[j+1,i-1])){
dp[j,i] = true;
if(j == 0) {
//0-i直接是回文
cut[i] = 0;
} else {
cut[i] = Math.Min(cut[j-1]+1, cut[i]);
}
}
}
}
return cut[len-1];
}
}
分割回文串
这道题用的不是递归,但鉴于跟上一题是一个系列的就写在这儿。
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: “aab”
输出:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]
链接:https://leetcode-cn.com/problems/palindrome-partitioning
public class Solution {
public List<IList<string>> result = new List<IList<string>>();
public List<string> current = new List<string>();
public IList<IList<string>> Partition(string s) {
BackTrack(s,0);
return result;
}
public void BackTrack(string s, int start){
if(start==s.Length) {
result.Add(new List<string>(current));
return;
}
for(var i=start;i<s.Length;i++){
if(IsPalindrome(s,start,i)){
if(start==i){
current.Add(s[i].ToString());
}
else{
current.Add(s.Substring(start, i+1-start));
}
BackTrack(s, i+1);
current.RemoveAt(current.Count - 1);
}
}
}
public bool IsPalindrome(string s, int i, int j){
while(i<j){
if(s[i++]!=s[j--]) return false;
}
return true;
}
}