Example of Recursion.

Here is an Example of recursion.

The codes are incentive to calculate all possible results if you have N tasks being delievered.

for more detail, please contact jimworks@gmail.com.

package forfun;

import java.util.ArrayList;
import java.util.Stack;


/**
 *
 * @author raymond
 */
public class Tsp {
    private Stack<Integer> sp;
    private Stack<Integer> sd = new Stack<Integer>();
    private Stack<Integer> sr = new Stack<Integer>();
    private int counter = 0;
    private ArrayList<ArrayList> alro = new ArrayList<ArrayList>();

    public ArrayList<ArrayList> getAlro() {
        return alro;
    }
    
    public Tsp(Stack<Integer> sp)            
    {
        this.sp = sp;
        this.sr.add(0);
        
        searchp(this.sp,sd,sr,sp.size());
    }
    
    private void searchp(Stack<Integer> p,Stack<Integer> d,Stack<Integer> r,int n)
    {

        int all = p.size()+d.size(); 
        
        for(int i=0;i<all;i++)
        {
            if(i<p.size())
            {
                int pp = p.get(i);
                int v1 = pp + n;
                d.push(v1); 
                r.push(pp);
                p.remove(i);
                searchp(p,d,r,n);
                r.pop();
                d.pop();
                p.add(i, pp);
            }
            else
            { 
                int dp = d.get(i-p.size());
                r.push(dp);
                d.remove(i-p.size());
                searchp(p,d,r,n);
                r.pop();
                d.add(i-p.size(),dp);
            }
        }
        
        if(d.isEmpty())
        { 
            ArrayList<Integer> alr = new ArrayList<Integer>();
            for(int j=0;j<r.size();j++)
            {
                alr.add(r.get(j));
            }   

//            alro.add(alr);
            counter ++;
        }  
       
    }

    public int getCounter() {
        return counter;
    }
    
    public static void main(String[] args) {
        Stack<Integer> sp = new Stack<Integer>();
        sp.push(1);
        sp.push(2);
        sp.push(3);
        sp.push(4);
        sp.push(5);
        sp.push(6);
        sp.push(7);
        Tsp t = new Tsp(sp);
        
        System.out.println("c="+(t.getCounter()-1));
        
//        ArrayList<ArrayList> alro = t.getAlro();
//        System.out.println("size="+(alro.size()-1));
        
        
//        for(int i=0;i<alro.size();i++)
//        {
//            ArrayList<Integer> s = alro.get(i);
//            for(int j=0;j<s.size();j++)
//            {
//                System.out.print(s.get(j) +" ");
//            }
//            System.out.println("");
//        }
            
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值