leetcode 140

#include <iostream>
#include<stdlib.h>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;

string str = "catsanddog";
vector<string> wordlist= { "cat", "cats", "and", "sand", "dog" };
vector<vector<string>>ans;//所有答案
vector<string>path;
bool cmp(string left, string right) {
	return left.length() < right.length() ? true : false;
}
void init() {
	sort(wordlist.begin(), wordlist.end(), cmp); 
//先按长度排序,减少后面遍历的情况;也可以
//用map存储前缀?以空间换时间-----
}
void print() {
    if(ans.size()==0){
        cout<<"no answer"<<endl;
        return;
    }
	for (int i = 0; i < ans.size(); i++) {
		for (int j = 0; j < ans[i].size(); j++)
			cout << ans[i][j]<< " ";
		cout << endl;
	}
}
//rest表示匹配剩下的字符串
void process(string rest) {
	if (rest == "") {
		ans.push_back(path);
		return;
	}
	for (int i = 0; i<wordlist.size() && wordlist[i].length() <= rest.length();i++) {
		if (rest.substr(0, wordlist[i].length()) == wordlist[i]) {
			path.push_back(wordlist[i]);
			process(rest.substr(wordlist[i].length()));
			path.pop_back();
		}
	}
}
int main() {
	init();
	process(str);
	print();
	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值