宁波做网站建设推广链接点击器
22. 括号生成
数字 n
代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3 输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1 输出:["()"]
提示:
1 <= n <= 8
class Solution {public List<String> generateParenthesis(int n) {List<String> list=new ArrayList<>();String str="";fangfa(str,n,0,0,list);return list;}public void fangfa(String str,int n,int lcount,int rcount,List<String> list){if (lcount==n&&rcount==n){list.add(str);return;}if(lcount<rcount||lcount>n||rcount>n) return;//左fangfa(str+"(",n,lcount+1,rcount,list);//右fangfa(str+")",n,lcount,rcount+1,list);}
}
46. 全排列
给定一个不含重复数字的数组 nums
,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例 1:
输入:nums = [1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
示例 2:
输入:nums = [0,1] 输出:[[0,1],[1,0]]
示例 3:
输入:nums = [1] 输出:[[1]]
提示:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
nums
中的所有整数 互不相同
class Solution {List<List<Integer>> list=new ArrayList<List<Integer>>();public List<List<Integer>> permute(int[] nums) {b(0,nums);return list;}public void b(int t,int[] x){if(t>=x.length){List<Integer> l=new ArrayList<>();for (int i = 0; i < x.length; i++) {l.add(x[i]);}list.add(l);}else {for (int i = t; i < x.length; i++) {// swap(x[t],x[i]);int temp=x[t];x[t]=x[i];x[i]=temp;b(t+1,x);// swap(x[t],x[i]);temp=x[t];x[t]=x[i];x[i]=temp;}}}
}
无剪枝条件、递归