Recursion problems

Problem 1: print out all of the permutations of n elements:

template <typename Iterator>
void perm(Iterator begin, Iterator end, Iterator i)
{
        if (i != end) {
                for (auto j = i; j != end; ++j) {
                        exchange(i, j);
                        perm<Iterator>(begin, end, i + 1);
                        exchange(i, j);
                }
        }
        else {
                std::for_each(begin, end, [](typename boost::call_traits<typename std::iterator_traits<Iterator>::value_type>::param_type n) {
                                std::cout << n < " ";
                        }
                );
                std::cout << std::endl;
        }
}

Problem 2: print out all of the reasonable permutations of n pairs of parenthesis.

void perm(char * begin, char * end, char * i, size_t left_count, size_t right_count)
{

        if (i < end) {
                size_t n = (end - begin)/2;
                if (left_count <= n && right_count <= n) {
                        if (left_count > right_count) {
                                *i = ')';
                                perm(begin, end, i + 1, left_count, right_count + 1);
                        }
                        *i = '(';
                        perm(begin, end, i + 1, left_count + 1, right_count);
                }
        }
        else {
                if (left_count == right_count) {
                        std::for_each(begin, end, [](char c) {std::cout << c;});
                        std::cout << std::endl;
                }
        }
}

Testing code:

int main()
{
        int data[] = {1, 2, 3, 4};
        perm(std::begin(data), std::end(data), std::begin(data));

        char buf[6];
        perm(std::begin(buf), std::end(buf), std::begin(buf), 0, 0);
        return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值