日期:2014-05-20  浏览次数:20587 次

求助关于排列组合的递归问题,树的问题,算法求知道
DNA 有4个核苷酸,A T C G,如果一小段有k个核苷酸串联在一起,每一个核苷酸可以4种选择,(比如(k=7) ATCGAAT,)  所以总共就有4的k次方种可能性。 现在要写个程序,把这所有的结果打印出来,或者存在数组容器里面。我知道当k是7时,直接用7个for 循环可以写,但是,如果k是个变量,可不可以用递归来做?而且这个有点像4叉树的模型遍历。
我写了代码,不知道错哪里了,求各位指点。


static String result = "";
String[] resource = new String[]{"A", "T", "C", "G"};
public void permKmer(String tempString, int index, int currentLevel, int maxLevel){

if(currentLevel == maxLevel){
System.out.println("the result of Kmer = " + result);
return;
}

//System.out.println("the current level " + currentLevel);
currentLevel++;
result = tempString + resource[index];
permKmer(result, 0, currentLevel, maxLevel);
System.out.println("   ");
permKmer(result, 1, currentLevel, maxLevel);
}

------解决方案--------------------

    public static void main(String[] args) {
        p(7, "");
    }

    public static void p(int i, String pre) {
        if (i == 0) {
            System.out.println(pre);
        } else {
            for (String s : new String[]{"A", "T", "C", "G"}) {
                p(i - 1, pre + s);
            }
        }
    }

------解决方案--------------------

static List<Character> candidates = new ArrayList<Character>();
public static void main(String[] args) {
candidates.add( 'A' );
candidates.add( 'T' );
candidates.add( 'C' );
candidates.add( 'G' );
int k = 2;
ArrayList<ArrayList<Character>> result = new ArrayList<ArrayList<Character>>();
ArrayList<Character> curList = new ArrayList<Character>();
permutation( k, 1, curList, result );
for( ArrayList<Character> res : result )
System.out.println( res );
}
public static void permutation( int k, int l, ArrayList<Character> curList, ArrayList<ArrayList<Character>> result ) {
if( l > k ) {
result.add( (ArrayList<Character>)curList.clone() );
return;
}
for( int i= 0; i < 4; i++  ) {
curList.add( candidates.get( i ) );
permutation( k, l+1, curList, result );
curList.remove( curList.size() - 1 );
}
}

------解决方案--------------------
月经题了,属于典型的解空间遍历问题,无非是两种解决方案:DFS和BFS


import java.util.LinkedList;
import java.util.Queue;
public class Select {
    
/**先序遍历法:深度搜索解空间  递归
 * @param array  数组
 * @param k      最多k层
 * @param level  当前层次
 * @param parent 父节点串
 */
public static void dfs(String[] array,int k,int level,String parent){
    if(level==k){
        count++;
        //System.out.println(parent);
    }else{
        for(int i=0;i<array.length;i++){
            dfs(array, k, level+1, parent+array[i]);
        }
        
    }
}
/**层序遍历法:广度搜索解空间  非递归
 * @param array
 * @param k
 */
public static void bfs(String[] array,int k){
    Node root=new Node(0, "");
    Queue<Node> queue=new LinkedList<Node>();
    queue.offer(root);
    Node p=null;
    Node child=null;
    while(queue.peek().level!=k){
        p=queue.poll();
        for(int i=0;i<array.length;i++){
            child=new Node(p.level+1, p.str+array[i]);
            queue.offer(child);