新农上路
- 积分
- 97
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-2-16
- 最后登录
- 1970-1-1
|
写了个答案。。感觉好丑陋。。
- public class FBparenthese {
- public ArrayList<String> parenses(String s){
- ArrayList<String> rst = new ArrayList<>();
- ArrayList<Character> path = new ArrayList<>();
- helper(s,rst,path,0,0);
- int len = 0;
- for(String ss : rst){
- if(ss.length() > len){
- len = ss.length();
- }
- }
- ArrayList<String> newrst = new ArrayList<>();
- for(String ss : rst){
- if(ss.length() == len){
- newrst.add(ss);
- }
- }
- return newrst;
- }
- private void helper(String s, ArrayList<String> rst,ArrayList<Character> path, int pos,int leftcount) {
- if(pos == s.length()){
- String ss ="";
- for(Character c: path){
- ss = ss + c;
- }
- if(!rst.contains(ss) && leftcount == 0){
- rst.add(ss);
- }
- return;
- }
- if(s.charAt(pos) == '('){
- //加到path
- path.add('(');
- helper(s,rst,path,pos+1,leftcount+1);
- path.remove(path.size()-1);
- //不加到path
- helper(s,rst,path,pos+1,leftcount);
- }else if(s.charAt(pos)==')'){
- if(leftcount > 0){
- //加
- path.add(')');
- helper(s,rst,path,pos+1,leftcount-1);
- path.remove(path.size()-1);
- //不加
- helper(s,rst,path,pos+1,leftcount);
- }else{
- helper(s,rst,path,pos+1,leftcount);
- }
- }else{
- path.add(s.charAt(pos));
- helper(s,rst,path,pos+1,leftcount);
- }
- }
- public static void main(String[] args) {
- FBparenthese fb = new FBparenthese();
- System.out.println(fb.parenses("(a)())()").toString());
- }
- }
复制代码 |
|