aisensiy 2009-09-21 10:55
浏览 250
已采纳

求一可重复排列算法

{a, b, c}
要求生成长度为N的排列算法。
如长度为2:
[a, a]
[a, b]
[a, c]
[b, a]
[b, b]
[b, c]
[c, a]
[c, b]
[c, c]
[b]问题补充:[/b]
对递归总是模模糊糊的感觉...
我知道这个应该用递归,可是就是找不到一个可行的方案。
楼下的其他语言就让我更不明白了...算法么,还是接近C的好吧,大家看的是思路。
[b]问题补充:[/b]
这个算法能把递归改成非递归么~

  • 写回答

6条回答 默认 最新

  • lcf2025 2009-09-23 10:29
    关注

    抛个砖头,提供个思路
    [code="java"]
    public class testList {

    private int listLength; //生成排列的长度
    private List<Integer> sourceList;//源数据
    private List<List<Integer>> targetList;//生成的所有排列存放的容器
    
    
    public testList(int listLength,List<Integer> sourceList)
    {
        this.listLength = listLength;
        this.sourceList = sourceList;
        this.targetList = new LinkedList<List<Integer>>();
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        List<Integer> sourceList = new ArrayList<Integer>();
        for(int i=1;i<3;i++)
        {
            sourceList.add(i);
        }
    
        testList tl = new testList(4,sourceList);
    
        List<List<Integer>> targetList = tl.productList();
    
        System.out.println(targetList.size());
        for(int i=0;i<targetList.size();i++)
        {
            System.out.println(Arrays.toString(targetList.get(i).toArray()));
        }
    
    }
    
    public List<List<Integer>> productList()
    {
        if(listLength>0)
        {
            for(int i=0;i<sourceList.size();i++)
            {
                List<Integer> childList = new LinkedList<Integer>();
                addEle(childList,i);
            }
        }
        return this.targetList;
    }
    private void addEle(List<Integer> currentList,int index)
    {
        currentList.add(sourceList.get(index));
        if(currentList.size()<listLength)
        {
            for(int i=0;i<sourceList.size();i++)
            {
                List<Integer> childList = new LinkedList<Integer>();
                childList.addAll(currentList);
                addEle(childList,i);
            }
        }else if(currentList.size()==listLength)
        {
            targetList.add(currentList);
        }
    }
    

    }

    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题