输入:abc
输出:bac,cba,acb,bca,cab,abc
全排列的问题:
public ArrayList<String> Permutation(String str) { ArrayList<String> list = new ArrayList<String>(); if(str!=null && str.length()>0){ helper(str.toCharArray(),list,0); Collections.sort(list); } return list; } public void helper(char[] chars,ArrayList<String> list,int i) { if(i==chars.length-1) { list.add(String.valueOf(chars)); return; } else { for(int j=i;j<chars.length;j++) { if(i==j||chars[i]!=chars[j]) { swap(chars,i,j); helper(chars,list,i+1); swap(chars,j,i); } } } } private void swap(char[] cs,int i,int j){ char temp = cs[i]; cs[i] = cs[j]; cs[j] = temp; }
全组合:
public ArrayList<String> Comb(String str) { char[] chars = str.toCharArray(); ArrayList<String> list = new ArrayList<String>(); int combNum=1<<str.length(); for(int i=1;i<combNum;i++) { StringBuffer temp=new StringBuffer(); for(int j=0;j<str.length();j++) { int k=1<<j; if((k&i)!=0) { temp.append(chars[j]); } } if(!list.contains(temp.toString())) list.add(temp.toString()); } return list; }
打靶问题:
public int[] label= {0,1,2,3,4,5,6,7,8,9,10}; public void Compute(int score,int num,ArrayList<Integer> list){ if(score<0||score>(num+1)*10) return; if(num==0) { System.out.println(list); } for(int i=0;i<11;i++) { list.add(label[i]); Compute(score-label[i],num-1,list); list.remove(list.size()-1); } }
原文地址:https://www.cnblogs.com/smallJunJun/p/10560816.html
时间: 2024-11-08 19:52:07