93. 复原 IP 地址
思路: 基本就是回溯算法的模板,但本题需要一个全局int变量作为判断结束条件。
public class Solution {
private IList<string> result = new List<string>();
private IList<string> path = new List<string>();
private int count = 1;
public IList<string> RestoreIpAddresses(string s) {
BackTracking(s, 0);
return result;
}
public void BackTracking(string s, int startIndex)
{
if(count == 5 && startIndex >= s.Length)
{
result.Add(string.Join(".", path));
return;
}
for(int i = startIndex;i < s.Length;i++)
{
if(IsValid(s,startIndex,i))
{
path.Add(s.Substring(startIndex, i-startIndex+1));
}
else
{
continue;
}
count++;
BackTracking(s, i+1);
count--;
path.RemoveAt(path.Count - 1);
}
}
private bool IsValid(string s, int start, int end)
{
string tmp = s.Substring(start, end-start+1);
if(tmp.Length > 1 && tmp[0]=='0') return false;
else if(Int32.TryParse(tmp, out int result) &&result <=255 && result>=0) return true;
else return false;
}
}
78. 子集
public class Solution {
private IList<IList<int>> result = new List<IList<int>>();
private IList<int> path = new List<int>();
public IList<IList<int>> Subsets(int[] nums) {
BackTracking(nums, 0);
return result;
}
public void BackTracking(int[] nums, int startIndex)
{
List<int> tmp = new List<int>(); // 收集子集,要放在终止添加的上面,否则会漏掉自己
for(int i = 0;i < path.Count;i++)
{
tmp.Add(path[i]);
}
result.Add(tmp);
if(startIndex >= nums.Length)
{
return;
}
for(int i = startIndex;i < nums.Length;i++)
{
path.Add(nums[i]);
BackTracking(nums,i+1);
path.RemoveAt(path.Count - 1);
}
}
}
90. 子集 II
public class Solution {
private IList<IList<int>> result = new List<IList<int>>();
private IList<int> path = new List<int>();
public IList<IList<int>> SubsetsWithDup(int[] nums) {
BackTracking(nums, 0);
return result;
}
public void BackTracking(int[] nums, int startIndex)
{
List<int> tmp = new List<int>();
for(int i = 0;i < path.Count;i++)
{
tmp.Add(path[i]);
}
result.Add(tmp);
if(startIndex >= nums.Length)
{
return;
}
for(int i = startIndex;i < nums.Length;i++)
{
if(i > startIndex && nums[i] == nums[i-1])continue;
path.Add(nums[i]);
BackTracking(nums,i+1);
path.RemoveAt(path.Count - 1);
}
}
}