刷题05
组合
class Solution {
List<List<Integer>> sum=new LinkedList<>();
LinkedList<Integer> path=new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
get(n,k,1);
return sum;
}
public void get(int n,int k,int startIndex)
{
if(path.size()==k)
{
sum.add(new LinkedList<>(path));
return;
}
for(int i=startIndex;i<=n;i++)
{
path.add(i);
get(n,k,i+1);
path.removeLast();
}
}
}
组合总合Ⅲ
class Solution {
List<List<Integer>> sum=new LinkedList<>();
LinkedList<Integer> path=new LinkedList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
get(n,k,1);
return sum;
}
public void get(int n,int k,int startIndex)
{
if(path.size()==k&&n==0)
{
sum.add(new LinkedList<>(path));
return;
}
for(int i=startIndex;i<=9;i++)
{
path.add(i);
get(n-i,k,i+1);
path.removeLast();
}
}
}
电话号码组合
class Solution {
List<String> sum=new LinkedList<>();
StringBuilder sb=new StringBuilder();
public List<String> letterCombinations(String digits) {
if(digits.equals("")) return sum;
String[] nums={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
backtracking(digits,nums,0);
return sum;
}
public void backtracking(String digits,String[] nums,int startIndex)
{
if(sb.length()==digits.length())
{
sum.add(sb.toString());
return;
}
String str=nums[digits.charAt(startIndex)-'0'];
for(int i=0;i<str.length();i++)
{
sb.append(str.charAt(i));
backtracking(digits,nums,startIndex+1);
sb.deleteCharAt(sb.length()-1);
}
}
}
组合总合
class Solution {
List<List<Integer>> sum=new LinkedList<>();
LinkedList<Integer> path=new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
backtracking(candidates,target,0,0);
return sum;
}
public void backtracking(int[] candidates,int target,int startIndex,int count)
{
if(count==target)
{
sum.add(new LinkedList<>(path));
return;
}
for(int i=startIndex;i<candidates.length;i++)
{
if(count+candidates[i]>target) break;
path.add(candidates[i]);
count=count+candidates[i];
backtracking(candidates,target,i,count);
path.removeLast();
count=count-candidates[i];
}
}
}
组合总合Ⅱ
class Solution {
List<List<Integer>> sum=new LinkedList<>();
LinkedList<Integer> path=new LinkedList<>();
//Set<List<Integer>> set=new HashSet<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
boolean[] used=new boolean[candidates.length];
backtracking(candidates,target,0,0,used);
return sum;
}
public void backtracking(int[] candidates,int target,int startIndex,int count,boolean[] used)
{
if(count==target)
{
sum.add(new LinkedList<>(path));
// set.add(new LinkedList<>(path));
return;
}
for(int i=startIndex;i<candidates.length;i++)
{
if(i>0&&candidates[i]==candidates[i-1]&&used[i-1]==false)
{
continue;
// break;
}
if(count>target) return;
path.add(candidates[i]);
used[i]=true;
count+=candidates[i];
backtracking(candidates,target,i+1,count,used);
path.removeLast();
used[i]=false;
count-=candidates[i];
}
}
}