数字 n
代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3 输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1 输出:["()"]
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<String>();
backtrack(ans, new StringBuilder(), 0, 0, n);
return ans;
}
public void backtrack(List<String> ans, StringBuilder cur, int open, int close, int max) {
if (cur.length() == max * 2) {
ans.add(cur.toString());
return;
}
if (open < max) {
cur.append('(');
backtrack(ans, cur, open + 1, close, max);
cur.deleteCharAt(cur.length() - 1);
}
if (close < open) {
cur.append(')');
backtrack(ans, cur, open, close + 1, max);
cur.deleteCharAt(cur.length() - 1);
}
}
给你一个字符串 s
,请你将 s
分割成一些子串,使每个子串都是
回文串
。返回 s
所有可能的分割方案。
示例 1:
输入:s = "aab" 输出:[["a","a","b"],["aa","b"]]
示例 2:
输入:s = "a" 输出:[["a"]]
List<List<String>> lists=new ArrayList<>();
List<String> list=new ArrayList<>();
public List<List<String>> partition(String s) {
back(s,0);
return lists;
}
public void back(String s,int index){
if(index==s.length()){
lists.add(new ArrayList<>(list));
}
for(int i=index;i<s.length();i++){
if(huiwen(s.substring(index,i+1))){
list.add(s.substring(index,i+1));
back(s,i+1);
list.remove(list.size()-1);
}
else
continue;
}
}
public boolean huiwen(String s){
StringBuilder stringBuilder=new StringBuilder(s);
return stringBuilder.toString().equals(stringBuilder.reverse().toString());
}
给你一个整数数组 nums
,数组中的元素 互不相同 。返回该数组所有可能的
子集
(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3] 输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0] 输出:[[],[0]]
List<List<Integer>> lists=new ArrayList<>();
List<Integer> list=new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
back(nums,0);
return lists;
}
public void back(int[] nums,int index){
lists.add(new ArrayList<>(list));
if(index==nums.length)
return;
for(int i=index;i<nums.length;i++){
list.add(nums[i]);
back(nums,i+1);
list.remove(list.size()-1);
}
}