将递归算法转换为非递归实现

时间:2018-12-04 02:15:16

标签: recursion

public void selectString(List<List<String>> candidateList, List<String> selected, List<List<String>> results, int target) {

    if (CollectionUtils.isEmpty(candidateList)){
        return;
    }

    List<String> candidate = candidateList.get(0);

    for (String oneCandidate : candidate){
        if (selected.contains(oneCandidate)) continue;

        List<String> currentSelected = new ArrayList<>();
        currentSelected.addAll(selected);
        currentSelected.add(oneCandidate);

        if (currentSelected.size() >= target){
            results.add(currentSelected);
        }

        this.selectString(candidateList.subList(1, candidateList.size()), currentSelected, results, target);
    }

    return;
}

上面的代码是我写的置换递归算法,candidateList代表源列表,selected开头是空列表,结果代表最终结果,target代表候选人列表的大小。如何转换我的置换递归算法进入非递归实现?

0 个答案:

没有答案